简体   繁体   中英

Best way to get list of id's from hashMap values

I have a HashMap having Integer as keys and List<Employee> as values. I want to get all Ids from all Values of HashMap

List<Long> ids = new ArrayList<>();
    hm.forEach((key, value) -> {
        List<Integer> c = value.stream()
                .map(Employee::getId).collect(Collectors.toList());
        ids.addAll(c);
     }

Here is how I am trying to do so far. Is there a way to directly stream from values of HashMap and get all distinct values?

hm.values()
      .stream()
      .flatMap(List::stream)
      .map(Employee::getId)
      .collect(Collectors.toSet());

Since you are interested in Ids only, stream over values of HashMap , and since each of those are List (s), you would use flatMap , the rest is probably obvious. Also since these are distinct as you say, a return type of Set makes a lot more sense.

If you still require a List just use:

.... .map(Employee::getId)
     .distinct()
     .collect(Collectors.toList())
List<Long> ids = hm.values().stream().map(Employee::getId).collect(Collectors.toList());

Here what we have done is get values as stream and map employee id and collect as list.

Its not needed re add to list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM