Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pulling a List of Values from a Map given a List of Keys on Java 8

Tags:

java

java-8

I feel embarrassed that I am stuck on this but I am trying to pull the List of Strings (List<String>) from the Map<MyEnum, String> given then List of enum keys List<MyEnum>. The List<MyEnum> may or may not contain entries.

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 am looking for a Java 8 way to do this. Such as...

map.stream().map(e->?????)
like image 368
jiveturkey Avatar asked Feb 01 '18 20:02

jiveturkey


1 Answers

fields.stream()
      .map(map::get)
      .filter(Objects::nonNull)
      .collect(Collectors.toList())
like image 80
Eugene Avatar answered Nov 14 '22 21:11

Eugene