Skip to content
Advertisement

How to reduce a limited stream (e.g. an ArrayList) from right in Java?

I would like to convert a list to a self-implemented linked list using reduce. I managed to do that in a reverse order:

import java.util.Arrays;
import java.util.List;

public class Reverse {
    static class Node {
        int val;
        Node next;

        Node(int v, Node n) {
            val = v;
            next = n;
        }
    }

    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
        Node result = numbers
                .stream()
                .reduce(null,
                        (node, val) -> new Node(val, node),
                        (n1, n2) -> new Node(-1, null));

        while(result != null) {
            System.out.println(result.val);
            result = result.next;
        }
    }
}

Output is

6
5
4
3
2
1

I think to obtain result in the correct order, I may have to use something like foldRight or reduceRight in other languages. Does java provide anything similar, given that the stream is guaranteed to be limited?

Advertisement

Answer

As of the newest Java 16, the current Stream API doesn’t provide any operations “from the right” such as “reduceRight`.

The only possible workaround is to use Collections#reverse(List) method to reverse the order of the items in the collection right before applying reduction.

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
Collections.reverse(numbers);
Node result = numbers
    .stream()
    .reduce(null,
            (node, val) -> new Node(val, node),
            (n1, n2) -> new Node(-1, null));

Read more here: Java 8 stream reverse order

Advertisement