如何分组到地图中并更改密钥类型 [英] How to groupingBy into a Map and change the key type

查看:60
本文介绍了如何分组到地图中并更改密钥类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个代码,假定将交易对象的列表分为2类;

I have a code which is suppose to group a list of transaction objects into 2 categories;

public class Transaction {
    public String type;
    public Integer amount;
}

以下功能通过检查条件将列表分为2类.流操作的输出映射为Map<Boolean, List<Transaction>>,但我想使用String作为其键.所以我手动将它们转换.

The following function divided the list into 2 categories by checking a condition. The output map of the stream operation is Map<Boolean, List<Transaction>>, but I would like to use a String as its key. So I converted them manually.

public static Map<String, List<Transaction>> partitionTransactionArray(List<Transaction> t1) {
    Map<Boolean, List<Transaction>> result = list.stream().collect(Collectors.groupingBy(e -> ((e.type.equals("BUY") || e.type.equals("SELL")) && e.amount < 1000)));

    // I think this is not necessary
    Map<String, List<Transaction>> result1 = new HashMap<>();
    result1.put("APPROVED", result.get(true));
    result1.put("PENDING", result.get(false));

    return result1;
}

但是,我认为必须有一种巧妙的方法,使我可以在单个流操作中执行此操作.

However, I think there must be a clever way that allows me to do this operation in a single stream operation.

有人可以帮忙吗?

如果我想返回一个Map<String, List<Integer>>,而不是返回一个Map<String, List<Transactions>>,而该列表仅包含交易金额,该怎么办?

What if, instead of having a Map<String, List<Transactions>> returned, I want to have a Map<String, List<Integer>> returned where the List contains only the amount of the transaction.

如何在单个流操作中做到这一点?

How can I do it in a single stream operation?

推荐答案

替换

((e.type.equals("BUY") || e.type.equals("SELL")) && e.amount < 1000)

通过

((e.type.equals("BUY") || e.type.equals("SELL")) && e.amount < 1000) ? "APPROVED" : "PENDING"

您可能应该使用枚举代替魔术字符串常量.

You should probably use an enum instead of magic string constants.

这篇关于如何分组到地图中并更改密钥类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆