First note that the LinkedList class is already available in the JDK, and directly provides the .stream() method. I would recommend using this standard implementation if possible.
If you still want to use your custom class ListNode, a good way to obtain a stream from it is to :
- make
ListNodeimplementjava.lang.Iterableinterface, - call
StreamSupport.stream(listNodeInstance.spliterator(), false)
in Java 8 we have only Stream::iterate with 2 arguments: the initial element and a function to produce a new element from previous one, but you have to make this stream finite and one way of doing this is by using Stream::limit and by passing linked list size (which you should have even in a basic implementation):
Stream.iterate(node1, ListNode::getNext)
.limit(4) //linked list size
.forEach(n -> {
System.out.println(n.val);
});
You can use the other reduce operator, doing
static Node reverse(List<Integer> list) {
return list.stream()
.reduce(
(Node) null, //the empty element
(n, i) -> new Node(i, n) , //combining a Node and an Integer
(n1, n2) -> new Node(n1.value, n2)); // could be anything
}
Edit: To make it work with parallelStream:
public static Node merge(Node n1, Node n2) {
if (n1 == null) {
return n2;
} else {
return new Node(n1.value, merge(n1.next, n2));
}
}
static Node reverse(List<Integer> list) {
return list.stream()
.reduce(
(Node) null, //the empty element
(n, i) -> new Node(i, n) , //combining a Node and an Integer
(n1, n2) -> merge(n1, n2)); // combining two Nodes
}
The problem you have is that reduce is expect to return the same type it accumulates. In this case null is an Integer as is a
What you can do is map each Integer to a Node and then reduce the Nodes into a linked list.
static Node reverse(List<Integer> list) {
return list.stream()
.map(i -> new Node(i, null))
.reduce(null, (a, b) -> {
b.next = a;
return b;
});
}
void run() {
List<Integer> list = IntStream.range(0, 3)
.boxed()
.collect(Collectors.toList());
Node reversed = reverse(list);
for(Node n = reversed; n != null ; n = n.next)
System.out.println(n.value);
}
prints
2
1
0