【问题标题】:Grouping in arrayList of arrayList在arrayList的arrayList中分组
【发布时间】:2019-05-26 14:25:21
【问题描述】:

您好,我有一个 ArrayList 的字符串 ArrayList。示例如下:

  [[765,servus, burdnare],
   [764,asinj, ferrantis],
   [764,asinj, ferrantis],
   [764,asinj, ferrantis],
   [762,asinj, ferrantis],
   [756,peciam terre, cisterne],
   [756,peciam terre, cortile],
   [756,peciam terre, domo],
   [756,asinj, ferrantis]]

是否可以为索引 0 的每个值在索引 1 处获取唯一值列表...我期望的结果是:

765 - [servus]
764 - [asinj]
762 - [asinj]
756 - [peciam terre, asinj]

我尝试了一系列 if 语句,但是没有用

【问题讨论】:

标签: java arraylist java-8


【解决方案1】:

您可以按 index-0 元素进行分组,并在 Set 中收集 index-1 元素以获得唯一性

List<List<String>> listOfList = ...//

Map<String, Set<String>> collect = listOfList.stream()
        .filter(l -> l.size() >= 2)
        .collect(Collectors.groupingBy(l -> l.get(0), Collectors.mapping(l -> l.get(1), Collectors.toSet())));

【讨论】:

    【解决方案2】:

    一种可能的变体。只需遍历给定列表并使用所需的keySet 作为忽略重复项的值构建Map

    public static Map<String, Set<String>> group(List<List<String>> listOfList) {
        Map<String, Set<String>> map = new LinkedHashMap<>();
    
        listOfList.forEach(item -> map.compute(item.get(0), (id, names) -> {
            (names = Optional.ofNullable(names).orElseGet(HashSet::new)).add(item.get(1));
            return names;
        }));
    
        return map;
    }
    

    【讨论】:

      【解决方案3】:

      假设你有一个List&lt;List&lt;String&gt;&gt; 作为源,你可以使用forEach + computeIfAbsent

      Map<String, Set<String>> map = new HashMap<>();
      list.forEach(l -> map.computeIfAbsent(l.get(0), k -> new HashSet<>()).add(l.get(1)));
      

      【讨论】:

        猜你喜欢
        • 2018-08-16
        • 2020-01-10
        • 1970-01-01
        • 2016-07-01
        • 1970-01-01
        • 2013-05-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多