Java stream on specific fields in a custom class object

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 =>x.getDestination()).distinct().collect(Collectors.toList());
List<String> list2 =>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?

>Solution :

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 =
          .flatMap(t -> Stream.of(t.getSource(), t.getDestination()))

Leave a Reply