Blackout Roulette Blackout Roulette - 2 months ago 16
Java Question

Java 8 Stream: 1 Object to 2 Objects

Is it possible to do something like this with the Stream API?

LinkedList<Point> l = new LinkedList<>();
for(Edge e : EDGES){
l.add(e.p1);
l.add(e.p2);
}


I want to get Point A and Point B from 3 Edges of a Triangle and eliminate the duplicates with .distinct

Answer

You can generate a Stream of all the Points of all the edges using flatMap and remove the duplicates with distinct() :

LinkedList<Point> l =
    EDGES.stream()
         .flatMap(e->Stream.of(e.p1,e.p2))
         .distinct()
         .collect(Collectors.toCollection(LinkedList::new);
Comments