我有一个代码,假设将事务对象列表分为两类;
public class Transaction {
public String type;
public Integer amount;
}
以下功能通过检查条件将列表分为2类。流操作的输出映射是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"
您应该使用枚举而不是魔术字符串常量。
您可以使用partitioningBy
将groupingBy
下游用于Collectors.mapping
而不是Map<Boolean, List<Integer>> result = list.stream()
.collect(Collectors.partitioningBy(e ->
((e.type.equals("BUY") || e.type.equals("SELL")) && e.amount < 1000),
Collectors.mapping(Transaction::getAmount, Collectors.toList())));
:
qazxswpoi