Java program to collect successive pairs from a stream API

By | March 23, 2023

To collect successive pairs from a stream API in Java, you can use the IntStream interface which provides a method called range to generate a range of integers, and the Stream interface which provides a method called iterate to generate a sequence of values based on a given function. Here’s an example:

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

List<int[]> pairs = IntStream.range(0, numbers.size() – 1)

                             .mapToObj(i -> new int[]{numbers.get(i), numbers.get(i + 1)})

                             .collect(Collectors.toList());

pairs.forEach(pair -> System.out.println(Arrays.toString(pair)));

In the above example, we first create a list of Integer objects. We then call the IntStream.range method to generate a range of integers from 0 to the size of the list minus one. We use this range of integers to generate a sequence of pairs of successive elements from the list using the mapToObj method. The mapToObj method takes a function that maps each integer in the range to an array containing the corresponding element and the next element from the list. We then collect the resulting sequence of pairs into a list using the collect method with Collectors.toList(). Finally, we print each pair using a forEach loop.

The output of the above code will be:

[1, 2]

[2, 3]

[3, 4]

[4, 5]

Note that we’re using an int[] array to store each pair of integers. If you need to use a different type, you can modify the mapToObj function accordingly.

Leave a Reply

Your email address will not be published. Required fields are marked *