Skip to content
Advertisement

Initialize a Linked List nodes using map().reduce()

I want to do this initialization of the Node class using java streams. How do I do this using the map and reduce stream operations?

Node node5 = new Node(5,null);
Node node4 = new Node(4,node5);
Node node3 = new Node(3,node4);
Node node2 = new Node(2,node3);
Node node1 = new Node(1,node2);

I’ve tried something like this, which does not compile

Node node = Arrays.stream(new int[]{1,2,3,4,5})
    .map((i, n) -> new Node(i, n)
    .reduce(null, new SingleList.Node(i, n)));

I want to map each element in the array to Node(int i , Node n) and then reduce it to a Node. What am I missing here?

Advertisement

Answer

If you want to initialize a List of object Node with specific values of an array, and not from 0 to n, you could use the iterate operation to generate the indexes and traverse the array from the last element to the first one. Then, as you suggested, you could map every int to an Integer (or using the boxed operation) and then use the reduce operation to build your list starting from the bottom.

int[] vet = new int[]{7, 15, 6, 32, 44};
Node node = IntStream.iterate(vet.length - 1, i -> i >= 0, i -> i - 1)
        .mapToObj(i -> i)
        .reduce(null, (n, i) -> new Node(vet[i], n), (n1, n2) -> {
            throw new RuntimeException("No parallel execution supported");
        });

The previous code refers to a Node implementation like the following:

class Node {
    private int info;
    private Node next;

    public Node(int info, Node next) {
        this.info = info;
        this.next = next;
    }

    //... getters & setters ...
}

Output

Node temp = node;
while (temp != null) {
    System.out.println(temp.getInfo());
    temp = temp.next;
}

enter image description here

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement