【问题标题】:Grouping by List Values and find total number of elements which is used in List按列表值分组并查找列表中使用的元素总数
【发布时间】:2021-03-07 07:41:30
【问题描述】:

我有一个 List<<Map<String, Object>> 在 List 中包含以下值: Map 包含两个键 resourceName 和 tableName 如下图所示:

Map<String, Object> m1 = new HashMap<>();
m1.put("resourceName", "Pt");
m1.put("tableName", "Tb1");

Map<String, Object> m2 = new HashMap<>();
m2.put("resourceName", "Pt");
m2.put("tableName", "Tb2");

Map<String, Object> m3 = new HashMap<>();
m3.put("resourceName", "Enc");
m3.put("tableName", "Enctab1");

我想要如下所述的输出(即,每个资源的表名数:)

[铂,2] [编码,1]

【问题讨论】:

  • 请使用OS的代码格式编辑,从不发代码图片
  • @Ivan,感谢您的回复。我用代码 sn-p 替换了代码图像。您对这个问题的解决方案有任何想法吗?

标签: java collections java-8 java-stream


【解决方案1】:

试试这个:

List<Map<String, Object>> list = // ...

Map<Object, Long> frequencies = list.stream()
                                    .map(Map::values)
                                    .flatMap(Collection::stream)
                                    .collect(groupingBy(identity(), counting()));

确保有这些导入:

import static java.util.function.Function.identity;
import static java.util.stream.Collectors.counting;
import static java.util.stream.Collectors.groupingBy;

【讨论】:

    【解决方案2】:

    这里似乎有以下几点很重要:

    1. 通过地图中的特定键"resourceName" 选择和计数条目,
    2. 通过将Map.Entry 转换为字符串来表示所需格式的输出
    String result = list.stream()
        .map(m -> m.get("resourceName")) // retrieve specific 'field' from map
        .collect(Collectors.groupingBy(  // calculate frequency of values
            name -> name, 
            Collectors.summingInt(name -> 1)
        ))
        .entrySet().stream()
        .map(e -> Arrays.toString(new Object[]{e.getKey(), e.getValue()}))
        .collect(Collectors.joining());
    System.out.println(result);
    

    输出:

    [Pt, 2][Enc, 1]
    

    【讨论】:

      猜你喜欢
      • 2020-01-21
      • 2016-07-18
      • 2011-02-15
      • 2018-09-02
      • 1970-01-01
      • 2020-10-15
      • 2011-01-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多