Java 8分区列表

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

我知道可以使用Guava Lists类,但是我们可以使用纯Jdk吗? 我不想在我的项目中添加新的jar,仅用于一个用例。

解决方案

tagir-valeev提出了迄今为止最好的解决方案:

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

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

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

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

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

3.分隔符拆分:

 List 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> subSets = IntStream.range(0, indexes.length - 1) .mapToObj(i -> intList.subList(indexes[i] + 1, indexes[i + 1])) .collect(Collectors.toList()); 

这可以使用subList()方法轻松完成:

 List collection = new ArrayList(21); // fill collection int chunkSize = 10; List> lists = new ArrayList<>(); for (int i=0; i 

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

 public static Collection> splitListBySize(List 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; }