简体   繁体   中英

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

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

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM