Search code examples
javajava-streamflatmap

Obtain from a List custom Objects of a List of distinct String values of Two String fields of these Objects using Java-Streams


Java stream on specific fields in a custom class object

I have an ArrayList of Train objects.

Each Train has three fields: source, destination, cost.

I want to get all the place names, i.e. all distinct sources + destinations.

I am using the below code, but as it can be observed, I'm using two streams to retrieve the data.

List<String> destinations = list.stream()
    .map(x -> x.getDestination())
    .distinct()
    .collect(Collectors.toList());

List<String> sources = List.stream()
    .map(x -> x.getSource())
    .distinct()
    .collect(Collectors.toList());

I was wondering how I could accomplish the same thing in a single stream? Can it be done using flatMap, or there's another way to achieve this?

List<String> allPlaces = ?

Also, is this possible to use Train class without getters?


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());