【问题标题】:Java: Splitting array/list of elements into sublists of equal elementsJava:将数组/元素列表拆分为相等元素的子列表
【发布时间】:2019-09-24 18:32:10
【问题描述】:

给定一个这样的排序列表:

List<Integer> a = Arrays.asList(1, 1, 1, 2, 4, 5, 5, 7);

是否有一种单行方式将这个数组拆分为子列表,每个子列表都包含相同值的元素,例如:

List[List[1, 1, 1], List[2], List[4], List[5, 5], List[7]]

【问题讨论】:

    标签: java list split


    【解决方案1】:

    您可以流式传输List 的元素并使用Collectors.groupingBy() 对相同的元素进行分组。它会产生一个Map<Integer,List<Integer>>,你可以得到values()Collection

    Collection<List<Integer>> grouped =
        a.stream()
         .collect(Collectors.groupingBy(Function.identity()))
         .values();
    

    要获得List&lt;List&lt;Integer&gt;&gt;,您可以使用:

    List<List<Integer>> grouped = 
        new ArrayList<> (a.stream()
                          .collect(Collectors.groupingBy(Function.identity()))
                          .values());
    

    第二个 sn-p 生成 List:

    [[1, 1, 1], [2], [4], [5, 5], [7]]
    

    【讨论】:

      猜你喜欢
      • 2017-07-30
      • 1970-01-01
      • 2015-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-29
      • 2017-04-25
      相关资源
      最近更新 更多