Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 = 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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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 =
    trains.stream()
          .flatMap(t -> Stream.of(t.getSource(), t.getDestination()))
          .distinct()
          .collect(Collectors.toList());
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading