Java 8 Stream API Collector Issue

Daniel Gerber

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

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

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Java 8 Stream API Collector Issue

From Java

Understanding Spliterator, Collector and Stream in Java 8

From Dev

Java 8 Stream - Compiler Issue

From Dev

Java 8 Map KeySet Stream not working as desired for use in Collector

From Dev

Java 8 Stream - NullPointerException when working with Custom Collector

From Dev

How to group values from a list with Java Stream API (groupingBy collector)?

From Dev

Grouping By in java 8 Stream API

From Dev

Grouping By in java 8 Stream API

From Java

Java8 Stream grouping by with toMap issue

From Dev

Issue with advanced java 8 stream usage

From Dev

Scala to Java8 stream compatibility issue

From Dev

java 8 parallel stream confusion/issue

From Java

Java8: HashMap<X, Y> to HashMap<X, Z> using Stream / Map-Reduce / Collector

From Dev

Java 8 stream list collector memory allocation speed vs loop with preallocation

From Dev

Java8, Is there a filtering collector?

From Dev

Java 8 Streams groupingBy collector

From Java

Grouping by ranges with Java 8 Stream API

From Java

Java 8 stream API orElse usage

From Dev

Java 8 stream api key based merging

From Dev

Java 8: merge lists with stream API

From Dev

Is there an aggregateBy method in the stream Java 8 api?

From Dev

Java 8 Stream API equivalent of nested for loops

From Dev

Java 8 Stream API : Filter on instance, and cast

From Dev

Finding enum value with Java 8 Stream API

From Dev

Nested for loops to Java 8 Stream API representation

From Dev

Java 8 Stream API in Android N

From Dev

Java 8 Stream API toMap converting to TreeMap

From Dev

Java 8 stream api control output

From Dev

Java 8 stream API orElse usage

Related Related

HotTag

Archive