【问题标题】:How to group a list of objects by an attribute and then iterate the results using (Key, Value) pair?如何按属性对对象列表进行分组,然后使用 (Key, Value) 对迭代结果?
【发布时间】:2019-07-12 16:35:48
【问题描述】:

我想按属性对对象列表进行分组,然后使用 (Key, Value) 对迭代结果。

我在 Java 8 中找到了将具有属性的对象列表分组的方法,如下所示

// filteredPageLog has the filtered results from PageLog entity.

Map<String, List<PageLog>> results = 
filteredPageLog.stream().collect(Collectors.groupingBy(p -> p.getSessionId()));

但结果将只有条目集(在 entrySet 属性中有值)。 keySet 和 valueSet 将具有空值。我想迭代类似的东西

results.forEach((key,value) -> {
//logic
});

【问题讨论】:

  • 以您想要的方式完成:results.forEach((key,value) -&gt; { //logic });

标签: java java-8


【解决方案1】:

使用

results.entrySet().forEach(entry -> {
     var key = entry.getKey();
     var value = entry.getValue();
//logic
});

【讨论】:

  • 在这一行得到空指针异常 "results.entrySet().forEach(entry -> {" @talex
  • @MohammedShirhaan 这意味着results 为空。
  • 我调试时 entrySet 有值。 @talex
  • @null 那么是什么?
  • for (Map.Entry> entry : results.entrySet()) { String sessionId = entry.getKey(); List pageLogs = entry.getValue(); //逻辑 } // 这行得通
【解决方案2】:

虚拟map:

Map<String,String> map = new HashMap() {{
             put("1","20");
             put("2","30");
           }};

您可以通过两种方式做到这一点:

1. Map&lt;K, V&gt;.forEach() 期望 BiConsumer&lt;? super K,? super V&gt; 为 论点,以及BiConsumer&lt;T, U&gt; 摘要的签名 方法是accept(T t, U u)

map.forEach((keys,values) -> { String k = keys ;
                               String v= values;
                                //logic goes here
                              });

2. Map&lt;K, V&gt;.entrySet().forEach() 期望 Consumer&lt;? super T&gt; 为 参数,以及Consumer&lt;T&gt; 摘要的签名 方法是accept(T t)

map.entrySet().forEach((entry) -> { String k = entry.getKey();
                                    String v= entry.getValue();
                                    //logic goes here
                                   });       

【讨论】:

    【解决方案3】:

    Java 中没有元组。 Here你可以找到更详细的解释。您可以迭代键、值或条目,但不能迭代元组。

    【讨论】:

    • 没有元组是什么意思?
    • 表示没有像 Scala 那样的语法糖,例如,参见alexecollins.com/java-tuples。在 Java 中,你不能写 (key, value) 而不是 entry。仅作为 lambda 到重载方法,接收合适的功能接口。
    • 不能写can't write (key, value) instead of entry你确定吗?
    • 我忘记了 map.forEach(BiConsumer super K,? super V>),你的回答很完美。所以,在这种情况下,lambda 看起来像两个元素元组)
    • 没错!别担心我在检查你的概念。 :)
    猜你喜欢
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-25
    • 2014-09-03
    • 1970-01-01
    相关资源
    最近更新 更多