Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambda expression in JAVA 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 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?

like image 973
John Humanyun Avatar asked Jan 01 '18 09:01

John Humanyun


People also ask

Can lambda functions be nested?

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.

Can we use if condition in lambda expression Java?

The 'if-else' condition can be applied as a lambda expression in forEach() function in form of a Consumer action.

How do you write multiple statements in lambda expression?

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); };


1 Answers

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]
like image 135
Eran Avatar answered Oct 19 '22 22:10

Eran