【问题标题】:How to groupingBy into a Map and change the key type如何将 groupingBy 放入 Map 并更改键类型
【发布时间】:2019-04-21 18:44:50
【问题描述】:

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

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

以下函数通过检查条件将列表分为 2 类。流操作的输出映射是Map<Boolean, List<Transaction>>,但我想使用一个字符串作为它的键。所以我手动转换它们。

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&lt;String, List&lt;Transactions&gt;&gt;,而是希望返回一个Map&lt;String, List&lt;Integer&gt;&gt;,其中列表仅包含交易金额,该怎么办。

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

【问题讨论】:

    标签: java java-8 java-stream partitioning collectors


    【解决方案1】:

    替换

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

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

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

    【讨论】:

    【解决方案2】:

    您可以使用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())));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-18
      • 1970-01-01
      • 1970-01-01
      • 2011-07-28
      • 2014-08-06
      • 1970-01-01
      • 2013-05-08
      • 1970-01-01
      相关资源
      最近更新 更多