-1

I have used below program to find out all sublist from defined list. Please find below program

public static void sublist() {
        int position = 2;

        List<String> arrlist = new ArrayList<>();

        arrlist.add("A");
        arrlist.add("B");
        arrlist.add("C");
        arrlist.add("D");
        arrlist.add("E");

        System.out.println("Original arrlist: " + arrlist);

        for (int i = 0; i < arrlist.size(); i += position) {
            int k = arrlist.size() > i + position ? i + position : arrlist.size();

            List<String> arrlist2 = arrlist.subList(i, k);
            System.out.println("Sublist of arrlist: " + arrlist2);
        }
    }

Output::

Original arrlist: [A, B, C, D, E]
Sublist of arrlist: [A, B]
Sublist of arrlist: [C, D]
Sublist of arrlist: [E]

Above program working fine.

My question is that is there any other simple way using java 8?

Shiladittya Chakraborty
  • 4,270
  • 8
  • 45
  • 94
  • 1
    From Guava `Lists.partition` would do this job. Take a look at https://www.geeksforgeeks.org/java-guava-lists-partition-method-with-examples/ Also here is a collection of methods to partition a List: https://www.baeldung.com/java-list-split – csalmhof Jul 15 '21 at 11:23

1 Answers1

1

If you want to use Java 8 Streams, you can use an 'IntStream' like this:

List<List<String>> arrlist2 =
    IntStream.range(0, arrlist.size())
        .filter(i -> i % position == 0)
        .mapToObj(i -> arrlist.subList(i, Math.min((i + position), arrlist.size())))
        .collect(Collectors.toList());

An output this List with System.out.println(arrlist2); will look as followed:

[[A, B], [C, D], [E]]

Important is the special case handling if the last partition is smaller than the size of the other partitions.

Otherwise you can also use Lists.partition from Java Guava (see https://www.geeksforgeeks.org/java-guava-lists-partition-method-with-examples/)


Since Java 9 you can also use IntStream.iterate like this:

List<List<String>> arrlist3 =
    IntStream.iterate(0, i -> i < arrlist.size(), i -> i + position)
        .mapToObj(i -> arrlist.subList(i, Math.min((i + position), arrlist.size())))
        .collect(Collectors.toList());
csalmhof
  • 1,820
  • 2
  • 15
  • 24
  • Instead of `range` and `filter`, you can use `IntStream.iterate(0, i -> i < arrlist.size(), i -> i += position)` – k314159 Jul 15 '21 at 11:43
  • @k314159 This method would only work since Java 9, however i also added this to the answer. Thanks – csalmhof Jul 15 '21 at 12:00