Pulling a list of values ​​from a map based on a list of keys in Java 8

I am ashamed that I am stuck on this, but I am trying to get the list of strings ( List<String>) out of the Map<MyEnum, String>then specified List of enum keys List<MyEnum>. List<MyEnum>may or may not contain records.

Edit:

List<String> toReturn = new ArrayList<>();

for (MyEnum field : fields) {
    String value = null;
    if ((value = map.get(field)) != null) {
       toReturn.add(value);
    }
}
return toReturn;

But I'm looking for a Java 8 way to do this. Such as...

map.stream().map(e->?????)
+4
source share
1 answer
fields.stream()
      .map(map::get)
      .filter(Objects::nonNull)
      .collect(Collectors.toList())
+6
source

Source: https://habr.com/ru/post/1693045/


All Articles