Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 623
Daniel Gerber Avatar asked Sep 14 '26 00:09

Daniel Gerber


2 Answers

Set<Vertex> vertices = edges.stream()
    .flatMap(e -> Stream.of(e.getSource(), e.getTarget()))
    .collect(Collectors.toSet());
like image 141
Misha Avatar answered Sep 15 '26 14:09

Misha


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);
like image 38
assylias Avatar answered Sep 15 '26 13:09

assylias



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!