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?