Daniel Gerber
Daniel Gerber

Reputation: 3470

Java 8 Stream API Collector Issue

I'm traversing a graph by its edges and want to have a list of all sources and targets. This is what I have so far:

public Set<Vertex> getVertices(){

    Set<Vertex> vertices = this.edges.stream().map(edge -> edge.getSource()).collect(Collectors.toSet());
    vertices.addAll(this.edges.stream().map(edge -> edge.getTarget()).collect(Collectors.toSet()));
    return vertices;
}

Is there any way to get both source and target in the same mapping/collection step? Something like (PSEUDO-CODE):

edges.stream().collect(edge.getSource()).collect(edge.getTarget())

Or plain old Java 7

for ( Edge e : edges ){
    vertices.add(e.getSource());
    vertices.add(e.getTarget());
}

Cheers, Daniel

Upvotes: 2

Views: 245

Answers (2)

assylias
assylias

Reputation: 328598

Yoy can use Misha's suggestion or write the collector manually:

Set<String> vertices = this.edges.stream()
       .collect(HashSet::new, (set, edge) -> {
            set.add(edge.getSource());
            set.add(edge.getTarget());
          }, Set::addAll);

Upvotes: 6

Misha
Misha

Reputation: 28133

Set<Vertex> vertices = edges.stream()
    .flatMap(e -> Stream.of(e.getSource(), e.getTarget()))
    .collect(Collectors.toSet());

Upvotes: 7

Related Questions