開發中有須要分批獲取list集合中的元素,如今查詢有以下幾種實現方法:code
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 0); //計算頁數 int limit = (list.size() + MAX_NUMBER - 1) / MAX_NUMBER;
/* ----------------------使用流對list進行分割--------------------------*/ List<List<Integer>> subList = new ArrayList<>(); Stream.iterate(0, n -> n + 1).limit(limit).forEach(i -> subList.add(list.stream().skip(i * MAX_NUMBER).limit(MAX_NUMBER).collect(Collectors.toList())) ); System.out.println(subList); /* ----------------------使用流對list進行分割--------------------------*/ List<List<Integer>> subList0 = Stream.iterate(0, n -> n + 1).limit(limit).parallel() .map(a -> list.stream().skip(a * MAX_NUMBER).limit(MAX_NUMBER).parallel().collect(Collectors.toList()) ).collect(Collectors.toList()); System.out.println(subList0);
List<List<Integer>> supList1 = Lists.partition(list, MAX_NUMBER); System.out.println(supList1);
List<List<Integer>> subList2 = ListUtils.partition(list, MAX_NUMBER); System.out.println(subList2);
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [0]] [[1, 2, 3], [4, 5, 6], [7, 8, 9], [0]] [[1, 2, 3], [4, 5, 6], [7, 8, 9], [0]] [[1, 2, 3], [4, 5, 6], [7, 8, 9], [0]]
若有問題還請指出哈,若是還有別的方法也請留言。ip