0

I have a class that contains the user data.

public class UserData {
    @JsonProperty("uid")
    private String userId;

    @JsonProperty("cities")
    private List<Integer> cities;

}

From the List<UserData>, I want to extract all the unique cities. Changes, I am doing for this,

Set<Integer> citiesList = new HashSet<>();

for (UserData userData : userDataList)
       citiesList.addAll(userData.getCities());

What could be the lambda expressions of these changes?

Any help would be much appreciated.

Karol Dowbecki
  • 43,645
  • 9
  • 78
  • 111
Vikas Gupta
  • 10,779
  • 4
  • 35
  • 42

2 Answers2

8

It feels like you should use .flatMap() with List.stream() operation, not a specific lambda expression:

Set<Integer> citiesList = userDataList.stream()
  .map(UserData::getCities)
  .flatMap(List::stream)
  .collect(Collectors.toSet());
Karol Dowbecki
  • 43,645
  • 9
  • 78
  • 111
1

If you want to be sure that the returned Set is a HashSet, you must use Collectors.toCollection(HashSet::new), like this:

userDataList.stream().map(d -> d.getCities())
      .flatMap(d -> d.stream())
      .collect(Collectors.toCollection(HashSet::new));
JMSilla
  • 1,326
  • 10
  • 17