我有一个代码可以将交易对象列表分为两类;
public class Transaction {
public String type;
public Integer amount;
}
以下函数通过检查条件将列表分为两类。流操作的输出映射为Map<Boolean, List<Transaction>>
,但我想使用 String 作为它的键。所以我手动转换了它们。
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;
}
但是,我认为一定有一种聪明的方法可以让我在单流操作中完成这个操作。
有人可以帮忙吗?
编辑:
如果不是 Map<String, List<Transactions>>
呢?返回了,我想要一个Map<String, List<Integer>>
在 List 仅包含交易金额的情况下返回。
如何在单流操作中完成?
最佳答案
替换
((e.type.equals("BUY") || e.type.equals("SELL")) && e.amount < 1000)
由
((e.type.equals("BUY") || e.type.equals("SELL")) && e.amount < 1000) ? "APPROVED" : "PENDING"
您可能应该使用枚举而不是神奇的字符串常量。
关于java - 如何将 groupingBy 放入 Map 并更改键类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55785686/