Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Properly terminate java stream

neighboursOfCurrentVertexList = neighboursOfCurrentVertexList.stream()
            .filter(vertex -> !vertex.isMarked())
            .map(vertex -> {
                vertex.setMarked(true);
                queueToVisitVertex.add(vertex);
                return vertex;
            }).collect(Collectors.toList());

I have implemented this breadthFirstSearch algorithm using java streams. First, i filtered to check if the vertex is marked, then if it is not marked, i add it to the queue. When i am using the .map, i need to end off with a terminating operation like .collect(Collectors.toList()).

My question is that this does not look right to me because I am using collect which returns a new list of the filtered vertex. What terminal operation should i be using in this case? I have no need of collecting the new list. I just want to use the map operation that is all. Thank you

like image 235
Ninja Dude Avatar asked Dec 09 '25 03:12

Ninja Dude


1 Answers

Use .forEach instead of .map:

neighboursOfCurrentVertexList.stream()
        .filter(vertex -> !vertex.isMarked())
        .forEach(vertex -> {
            vertex.setMarked(true);
            queueToVisitVertex.add(vertex);
        });
like image 56
Blorgbeard Avatar answered Dec 11 '25 16:12

Blorgbeard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!