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?
A lambda function inside a lambda function is called a nested lambda function. Python allows lambda nesting, i.e., you can create another lambda function inside a pre-existing lambda function. For nesting lambdas, you will need to define two lambda functions – an outer and an inner lambda function.
The 'if-else' condition can be applied as a lambda expression in forEach() function in form of a Consumer action.
Unlike an expression lambda, a statement lambda can contain multiple statements separated by semicolons. delegate void ModifyInt(int input); ModifyInt addOneAndTellMe = x => { int result = x + 1; Console. WriteLine(result); };
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 null
s.
Output:
[One, Two, Three]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With