I'm trying to learn Java Stream API and I'm writing some examples.
So my example is as follows:
I have a list of lists, every list can contain many nodes.
I want a program that checks and returns a node that fulfills some criterion.
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class Main {
public static void main( String[] args ) {
ArrayList<ArrayList<Node>> lists = new ArrayList<>();
/*here i'm creating a list of 10 list from 0 to 9
* and each list will have one node, the nodes will have a random
degree
*/
IntStream.range(0,10).forEach( index -> {
lists.add(new ArrayList<>());
int random=new Random().nextInt(10) + 1;
lists.get(index).add(new Node(random));
});
Node specificLsit = getaSpecificNode(lists);
}
/*we chould retun a new Node(1) if there is a node that have a degree=1
*and a new Node(2) id there is a node with degree= 2
*or null if the above condition fails.
*so what is the java stream operation to writre for that purpose.
*/
private static Node getaSpecificNode( ArrayList<ArrayList<Node>> lists ) {
Node nodeToReturn =null;
//code go here to return the desired result
return nodeToReturn;
}
}
class Node{
int degree;
Node(int degree){
this.degree = degree;
}
@Override
public String toString() {
return this.degree+"";
}
}
The 2 for loop is easy to solve the problem, but I want a solution that uses the stream api.
What I have tried :
private static Node getaSpecificNode( ArrayList<ArrayList<Node>> lists ) {
Node nodeToReturn =null;
lists.forEach((list)->{
list.forEach((node)->{
if (node.degree ==1 || node.degree ==2 )
nodeToReturn = node;
});
});
return nodeToReturn ;
}
Unfortunately I'm getting a compilation error that the variable nodeToReturn should be final, but in my case I'm trying to modify it.
Is there any better solution?