Ninja Dude
Ninja Dude

Reputation: 1392

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

Upvotes: 3

Views: 1701

Answers (1)

Blorgbeard
Blorgbeard

Reputation: 103467

Use .forEach instead of .map:

neighboursOfCurrentVertexList.stream()
        .filter(vertex -> !vertex.isMarked())
        .forEach(vertex -> {
            vertex.setMarked(true);
            queueToVisitVertex.add(vertex);
        });

Upvotes: 4

Related Questions