- Using ‘if-else’ Conditions with Java Streams
- If Condition in Lambda Expression Java
- If Condition
- 1. The If Condition Combined with Predicates
- 2. Consumer Implementation of the «if-else» Condition
- 3. Conventional if/else Logic Inside of forEach ()
- 4. if/else Logic Combined With a filter()
- Benefits of the Lambda Expression
- If condition in lambda expression to change value in java
- Lambda expression in JAVA for Nested Conditions
- Lambda expression example with multiple statements
- Java8 lambda grouping with condition
- Java Lambda’s Parse down a Collection with a Conditional Check
Using ‘if-else’ Conditions with Java Streams
Learn to use the if-else conditions logic using Java Stream API to filter the items from a collection based on certain conditions.
1. The ‘ if-else ‘ Condition as Consumer Implementation
The ‘if-else’ condition can be applied as a lambda expression in forEach() function in form of a Consumer action.
Consumer is a functional interface whose functional method is ‘ void accept(Object) ‘. It represents an operation that accepts a single input argument and returns no result.
In the given example, we are checking if a number is even then print a message, else print another message for an odd number.
ArrayList numberList = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6)); Consumer action = i -> < if (i % 2 == 0) < System.out.println("Even number :: " + i); //Or any other user action we want to do >else < System.out.println("Odd number :: " + i); //Or any other user action we want to do >>; numberList.stream() .forEach(action);
- We can perform any kind of operation on the stream items instead of just printing the items to the console, e.g. storing the items to two separate lists or passing the items to other method calls.
- We can write as many if-else statements as required.
- We can also write the pass the Consumer implementation as an inline lambda expression to the forEach() function.
Arrays.asList(-1, 1, -2, 3, 4, -5, 6, 0).stream() .forEach( i -> < if (i == 0) < System.out.println("Number is 0"); >else if (i > 0) < System.out.println("Positive Number"); >else < System.out.println("Negative Number"); >> );
2. The ‘ if’ Condition with Predicates
If we intend to apply only ‘if’ logic then we can pass the condition directly do the filter() function as a Predicate.
In the given example, we are checking if a number is an even number then printing a message.
ArrayList numberList = new ArrayList<>(Arrays.asList(1,2,3,4,5,6)); Predicate isEven = i -> i % 2 == 0; numberList.stream() .filter(isEven) .forEach(System.out::println);
Using one of the above given two methods, we can apply any combination of if-else conditions in Java 8 stream elements.
If Condition in Lambda Expression Java
The new and significant lambda expression feature of Java was added in Java SE 8. It provides a clear and concise mechanism for describing a single-method interface using an expression. It is quite useful for a library’s collection. It is beneficial to sort through a collection of data, iterate it over it, and extract relevant data. The use of the Lambda expression allows for the implementation of an interface with such a functional interface. Code is saved in large amounts. A lambda expression avoids this problem by allowing the implementation to be provided without redefining the method.
Just the implementation code is written here. Java lambda expressions are considered functions; hence the compiler does not produce a .class file.
If Condition
For each valid input, the lambda function would return a value. If the condition is true in this case, the block will be returned, and if it is false, the block will be returned.
1. The If Condition Combined with Predicates
We can give the condition directly to the filter() procedure as a Predicate if we just want to use «if» logic.
In the example shown, we are determining whether a number is even before printing a message.
ArrayListnumberList = new ArrayList<>(Arrays.asList(9,8,7,6,5,4)); PredicateisEven = i ->i % 2 == 0; numberList.stream() .filter(isEven) .forEach(System.out::println);
2. Consumer Implementation of the «if-else» Condition
In the forEach() function, the «if-else» condition can be implemented as a lambda expression in the form of a Consumer action.
A functional interface called Consumer has a functional method called «void accept(Object)». It stands for an operation that only takes one input argument and produces no output.
In the example provided, if a value is even, a message will be printed; if it’s odd, a different message will be printed.
ArrayListnumberList = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6)); Consumer action = i -> < if (i % 2 == 0) < System.out.println("Even number :: " + i); //Or any other user action we want to do >else < System.out.println("Odd number :: " + i); //Or any other user action we want to do >>; numberList.stream() .forEach(action);
- Instead of just publishing the stream objects to the console, we may do anything with them, such as placing them in two different lists or passing them to other function calls.
- If necessary, set multiple if-else statements that can be written.
- Inline lambda expressions can be used to provide the Consumer implementation to the forEach() method.
Arrays.asList(-2, 1, -3, 4, 5, -6,6, 7, 0).stream() .forEach( i -> < if (i == 0) < System.out.println("Number is 0"); >else if (i> 0) < System.out.println("Positive Number"); >else < System.out.println("Negative Number"); >> );
3. Conventional if/else Logic Inside of forEach ()
Let’s first establish an Integer List, and then inside the Integer stream forEach() method, utilize standard if/else logic:
Listints = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); ints.stream() .forEach(i -> < if (i.intValue() % 2 == 0) < Assert.assertTrue(i.intValue() % 2 == 0); >else < Assert.assertTrue(i.intValue() % 2 != 0); >>);
The Java modulus function is used in our forEach method’s if-else logic to determine whether the number is an odd or even value.
4. if/else Logic Combined With a filter()
Second, let’s have a look at a more tasteful application that makes use of the Stream filter() technique:
StreamevenIntegers = ints.stream() .filter(i ->i.intValue() % 2 == 0); StreamoddIntegers = ints.stream() .filter(i ->i.intValue() % 2 != 0); evenIntegers.forEach(i ->Assert.assertTrue(i.intValue() % 2 == 0)); oddIntegers.forEach(i ->Assert.assertTrue(i.intValue() % 2 != 0));
In the example above, we used the Stream filter() function to divide the Integer List into two different Streams, one just for even integers and one for odd integers, in order to apply the if/else logic.
Benefits of the Lambda Expression
- Less Code: One of the main advantages of using lambda expressions is that there are fewer lines of code to write. We are aware that only a functional interface enables the use of lambda expressions. For instance, since Framework to address is a functional language, lambda expressions are simple to use.
- Support for parallel and sequential execution through the use of behaviour arguments in methods Java 8’s Stream API is used to pass the functions to collection methods. Now, it is up to the collection to decide whether to handle the elements sequentially or concurrently.
- More Efficiency When doing bulk operations on collections, we can obtain higher efficiency (parallel processing) by leveraging the Stream API as well as lambda expressions. Additionally, rather than using external iteration, lambda expressions make it possible to iterate collections internally.
If condition in lambda expression to change value in java
Solution 1: Use a : Note that instead of checking if a key is in the map with , I just used , and then filtered out the s. Output: Solution 2: A variant of Erans solution: Uses method references Uses instead of checking values => if would contain values, checking values would give a wrong result. For anyone from the .NET stack, the equivalent in C#/LINQ would be I know there are plenty of other good ways to do this without lambdas, but I would like to know how I can achieve this in Java using Java Lambdas? Solution: I think that is what you looking for and not a
Lambda expression in JAVA for Nested Conditions
HashMap map1= new HashMap(); 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 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?
List 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.
A variant of Erans solution:
- Uses method references
- Uses containsKey instead of checking null values => if map1 would contain null values, checking null values would give a wrong result.
List spelling = numbers.stream() .filter(map1::containsKey) .map(map1::get) .collect(Collectors.toList()); System.out.println (spelling);
another option would be to use the forEach construct:
List spelling = map1.keySet().stream() .filter(numbers::contains) .map(map1::get) .collect(Collectors.toList());
C# lambda filter by condition in sublist, You can use Any on the sub list. For example: filteredCorporationSuppliers.Where(s => s.Supplier.SupplierContacts.Any(c => c.Person?
Lambda expression example with multiple statements
Java Source Code here:http://ramj2ee.blogspot.com/2017/05/java-tutorial-lambda-expression
Duration: 2:16
Java8 lambda grouping with condition
Java8 and Lambdas — that’s my play for now. And another problem/question. I got grouping made with lamda that look like this:
Map> temp = foo.stream().flatMap(x -> x.getValue().stream()).flatMap( x -> x.getAnswers().stream()).collect( Collectors.groupingBy( zz -> zz.getQuestion(), Collectors.mapping(z -> z, Collectors.toList()) ) );
I got myself here from a list of Foo, a map of Question with aggregated List of Answers that users made.
QUESTION
is it possible to add condition while grouping?
In this example, my Question.class has a Double field called Weight, and some Questions got this field null or with a value of 0.0.
I don’t need them in my aggregated Map, so I was wondering can I add condition here, or do I need to iterate through resulting Map?
EDIT
foo is a list of Result.class, x.getValue() returns a List of AnswerSet.class, and x.getAnswers() return a list of Answer.class. Answer.class has a Question.class as a field
foo.stream() .filter(q -> q.weight != null && q.weight != 0.0) .
Java Lambda’s Parse down a Collection with a Conditional Check
I’m working with Java 8 Lambdas, and have had success with simple use cases. I come from a mixed background of Java and C# .NET so I’m familiar with lambda’s in code.
In my current use case I’m trying to return a List from a Collection named values. I’ve done this successfully like this
values.stream().map(x -> x).collect(Collectors.toList());
Relatively simple and straightforward. I’d like to do the same thing, but only add item’s from the Collection where a boolean flag on the item is set to true. I thought that would work like this
values.stream().map(x -> < if(x.isActive())return ((Model)x);>).collect(Collectors.toList())
But the compiler keeps showing this error : Type mismatch: cannot convert from List to List I believe the compiler should be smart enough to know the output type from the map function and indeed does on my original simplified example. That’s why I believe this is not the best way to do this.
For anyone from the .NET stack, the equivalent in C#/LINQ would be
values.Where(x => x.isActive()).ToList();
I know there are plenty of other good ways to do this without lambdas, but I would like to know how I can achieve this in Java using Java Lambdas?
I think that filter is what you looking for and not a map
values.stream().filter(x->x.isActive()).collect(Collectors.toList());
Java Lambda Expression for if condition, Your current problem is that you use directly a lambda expression. Lambdas are instances of functional interfaces. Your lambda does not have the