如何将 groupingBy 放入 Map 并更改键类型

ZZZ*_*ZZZ 5 java partitioning java-8 java-stream collectors

我有一个代码,应该将交易对象列表分为两类;

public class Transaction {
    public String type;
    public Integer amount;
}
Run Code Online (Sandbox Code Playgroud)

以下函数通过检查条件将列表分为 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;
}
Run Code Online (Sandbox Code Playgroud)

但是,我认为必须有一种巧妙的方法可以让我在单个流操作中完成此操作。

有人可以帮忙吗?

编辑:

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

我怎样才能在单个流操作中做到这一点?

JB *_*zet 1

代替

((e.type.equals("BUY") || e.type.equals("SELL")) && e.amount < 1000)
Run Code Online (Sandbox Code Playgroud)

经过

((e.type.equals("BUY") || e.type.equals("SELL")) && e.amount < 1000) ? "APPROVED" : "PENDING"
Run Code Online (Sandbox Code Playgroud)

您可能应该使用枚举而不是魔术字符串常量。