Lambda expression in JAVA for Nested Conditions

John Humanyun :

I have the following Map:

HashMap<String, String> map1= new HashMap<String, String>();
map1.put("1", "One");
map1.put("2", "Two");
map1.put("3", "Three");

I have a list numbers which contains ["1","2","3"]

I have to perform the following operations:

List<String> spelling= new ArrayList<>();
for (String num: numbers) {
    if (map1.containsKey(num)){
        spelling.add(map1.get(num))
    }
}

How can I write the above code using lambda Expressions?

Eran :

Use a Stream:

List<String> spelling = numbers.stream()
                               .map(map1::get)
                               .filter(Objects::nonNull)
                               .collect(Collectors.toList());
System.out.println (spelling);

Note that instead of checking if a key is in the map with containsKey, I just used get, and then filtered out the nulls.

Output:

[One, Two, Three]

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=470916&siteId=1