I have an ArrayList<Train> List
of class Train
which has three data fields (source, destination, cost). I want to get all the place names, i.e source destination places. I am using the below code, but as you can see, I could only come up with a way to do it with two streams.
List<String> list1 = List.stream().map(x->x.getDestination()).distinct().collect(Collectors.toList());
List<String> list2 = List.stream().map(x->x.getSource()).distinct().collect(Collectors.toList());
I was wondering how I could accomplish the same thing in a single stream. I coudn't think of a way to flatMap it or how I could achieve this. Also is this possible without the getters methods of class Train?
CodePudding user response:
You had the right idea with flatMap
- you can map a train to a stream that contains the source and destination, and then flatMap
it to you "main" stream:
List<String> allPlaces =
trains.stream()
.flatMap(t -> Stream.of(t.getSource(), t.getDestination()))
.distinct()
.collect(Collectors.toList());