问题 Java 8分区列表


是否可以将纯Jdk8中的List分区为相等的块(子列表)。

我知道使用番石榴是可能的 清单 上课,但我们可以用纯Jdk做吗?我不想在我的项目中添加新的jar,仅用于一个用例。

SOLUTONS

迄今为止最好的解决方案是由 tagir-valeev

我也发现了 其他三种可能性,但它们只适用于少数情况:

1.Collectors.partitioningBy()将列表拆分为2个子列表 - 如下所示:

intList.stream().collect(Collectors.partitioningBy(s -> s > 6));
    List<List<Integer>> subSets = new ArrayList<List<Integer>>(groups.values());

2.Collectors.groupingBy()将我们的列表拆分为多个分区:

 Map<Integer, List<Integer>> groups = 
      intList.stream().collect(Collectors.groupingBy(s -> (s - 1) / 3));
    List<List<Integer>> subSets = new ArrayList<List<Integer>>(groups.values());

3.分隔符拆分:

List<Integer> intList = Lists.newArrayList(1, 2, 3, 0, 4, 5, 6, 0, 7, 8);

    int[] indexes = 
      Stream.of(IntStream.of(-1), IntStream.range(0, intList.size())
      .filter(i -> intList.get(i) == 0), IntStream.of(intList.size()))
      .flatMapToInt(s -> s).toArray();
    List<List<Integer>> subSets = 
      IntStream.range(0, indexes.length - 1)
               .mapToObj(i -> intList.subList(indexes[i] + 1, indexes[i + 1]))
               .collect(Collectors.toList());

4721
2018-06-23 06:52


起源

您可以查看Guava源代码并相应地进行操作......? - Uwe Allner
在普通java中使用函数不是问题,但是JDK8在集合上有流量和操作的一些很棒的功能,我认为它比编写自己的代码更快。但那只是我的假设。 - Beri
我将其标记为可能重复,因为Java-8解决方案也可用。 - Tagir Valeev
是的,我看过那个问题,但我错过了Jdk8解决方案,谢谢:) - Beri
还讨论了 这里 - Holger


答案:


这可以很容易地使用 subList() 方法:

List<String> collection = new ArrayList(21);
// fill collection
int chunkSize = 10;
List<List<String>> lists = new ArrayList<>();
for (int i=0; i<collection.size(); i+= chunkSize) {
    int end = Math.min(collection.size(), i + chunkSize);
    lists.add(collection.subList(i, end));
}

14
2018-06-23 07:01





尝试使用此代码,它使用Java 8:

public static Collection<List<Integer>> splitListBySize(List<Integer> intList, int size) {

    if (!intList.isEmpty() && size > 0) {
        final AtomicInteger counter = new AtomicInteger(0);
        return intList.stream().collect(Collectors.groupingBy(it -> counter.getAndIncrement() / size)).values();
    }
    return null;
}

2
2017-07-30 12:32