JAVA lambda expression for nested conditions

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 numbers list that contains ["1","2","3"]

I need 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?

+5
source share
4 answers

Use 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 the key is on the map using containsKey , I just used get and then filtered out null s.

Output:

 [One, Two, Three] 
+14
source

Eran Solution Option:

  • Uses method references
  • Uses containsKey instead of checking null values ​​=> if map1 contains null values, checking null will give an incorrect result.

Code snippet:

 List<String> spelling = numbers.stream() .filter(map1::containsKey) .map(map1::get) .collect(Collectors.toList()); System.out.println (spelling); 
+5
source

another option is to use the forEach construct:

 numbers.forEach(n -> { if(map1.containsKey(n)) spelling.add(map1.get(n)); }); 
+2
source

try it

  List<String> spelling = map1.keySet().stream() .filter(numbers::contains) .map(map1::get) .collect(Collectors.toList()); 
+1
source

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


All Articles