As it almost but not really matches Optional, maybe you might reconsider the logic:

Java 8 has a limited expressiveness:

Optional<Elem> element = ...
element.ifPresent(el -> System.out.println("Present " + el);
System.out.println(element.orElse(DEFAULT_ELEM));

Here the map might restrict the view on the element:

element.map(el -> el.mySpecialView()).ifPresent(System.out::println);

Java 9:

element.ifPresentOrElse(el -> System.out.println("Present " + el,
                        () -> System.out.println("Not present"));

In general the two branches are asymmetric.

Answer from Joop Eggen on Stack Overflow
Top answer
1 of 5
39

As it almost but not really matches Optional, maybe you might reconsider the logic:

Java 8 has a limited expressiveness:

Optional<Elem> element = ...
element.ifPresent(el -> System.out.println("Present " + el);
System.out.println(element.orElse(DEFAULT_ELEM));

Here the map might restrict the view on the element:

element.map(el -> el.mySpecialView()).ifPresent(System.out::println);

Java 9:

element.ifPresentOrElse(el -> System.out.println("Present " + el,
                        () -> System.out.println("Not present"));

In general the two branches are asymmetric.

2 of 5
21

It's called a 'fluent interface'. Simply change the return type and return this; to allow you to chain the methods:

public MyClass ifExist(Consumer<Element> consumer) {
    if (exist()) {
        consumer.accept(this);
    }
    return this;
}

public MyClass ifNotExist(Consumer<Element> consumer) {
    if (!exist()) {
        consumer.accept(this);
    }
    return this;
}

You could get a bit fancier and return an intermediate type:

interface Else<T>
{
    public void otherwise(Consumer<T> consumer); // 'else' is a keyword
}

class DefaultElse<T> implements Else<T>
{
    private final T item;

    DefaultElse(final T item) { this.item = item; }

    public void otherwise(Consumer<T> consumer)
    {
        consumer.accept(item);
    }
}

class NoopElse<T> implements Else<T>
{
    public void otherwise(Consumer<T> consumer) { }
}

public Else<MyClass> ifExist(Consumer<Element> consumer) {
    if (exist()) {
        consumer.accept(this);
        return new NoopElse<>();
    }
    return new DefaultElse<>(this);
}

Sample usage:

element.ifExist(el -> {
    //do something
})
.otherwise(el -> {
    //do something else
});
🌐
W3Schools
w3schools.com › java › java_lambda.asp
Java Lambda Expressions
Lambda Expressions were added in Java 8. A lambda expression is a short block of code that takes in parameters and returns a value. Lambdas look similar to methods, but they do not need a name, and they can be written right inside a method body.
Discussions

How to perform nested 'if' statements using Java 8/lambda? - Stack Overflow
I have the following code and would like to implement it using lambda functions just for fun. Can it be done using the basic aggregate operations? List result = new ArrayList More on stackoverflow.com
🌐 stackoverflow.com
Using lambda expressions for if statements - Code with Mosh Forum
Hello all! First post here haha, I’ll get right to it 🙂 I was recently asked as a challenge to represent a validation method as a lambda expression and the implication was that this was somehow more efficient/effective… I can’t see it 😕 does anyone here have experience doing this ... More on forum.codewithmosh.com
🌐 forum.codewithmosh.com
0
June 16, 2022
Java Lambda Expression for if condition - not expected here - Stack Overflow
Consider the case where an if condition needs to evaluate an array or a List. A simple example: check if all elements are true. But I'm looking for generic way to do it Normally I'd do it like tha... More on stackoverflow.com
🌐 stackoverflow.com
if statement - Java 8 Lambda To Handle for > if > else - Stack Overflow
I need to run two different tasks based on a whole mess of filters I'm just now grasping the concept of Lambdas, so I guess my question is, how do you handle multiple "else" conditions containing More on stackoverflow.com
🌐 stackoverflow.com
🌐
Oracle
docs.oracle.com › javase › tutorial › java › javaOO › lambdaexpressions.html
Lambda Expressions (The Java™ Tutorials > Learning the Java Language > Classes and Objects)
If the Person instance does satisfy the criteria specified by tester, the method printPerson is invoked on the Person instance. Instead of invoking the method printPerson, you can specify a different action to perform on those Person instances that satisfy the criteria specified by tester. You can specify this action with a lambda expression.
🌐
Code with Mosh
forum.codewithmosh.com › t › using-lambda-expressions-for-if-statements › 13119
Using lambda expressions for if statements - Code with Mosh Forum
June 16, 2022 - Hello all! First post here haha, I’ll get right to it :slight_smile: I was recently asked as a challenge to represent a validation method as a lambda expression and the implication was that this was somehow more effic…
🌐
Javatpoint
javatpoint.com › if-condition-in-lambda-expression-java
if Condition in Lambda Expression Java - Javatpoint
if Condition in Lambda Expression Java with java tutorial, features, history, variables, programs, operators, oops concept, array, string, map, math, methods, examples etc.
🌐
TutorialsPoint
tutorialspoint.com › how-to-write-a-conditional-expression-in-lambda-expression-in-java
How to write a conditional expression in lambda expression in Java?
The conditional operator is used to make conditional expressions in Java. It is also called a Ternary operator because it has three operands such as boolean condition, first expression, and second expression. We can also write a conditional expression in lambda expression in the below program.
Find elsewhere
🌐
HowToDoInJava
howtodoinjava.com › home › java 8 › using ‘if-else’ conditions with java streams
Using 'if-else' Conditions with Java Streams - HowToDoInJava
March 3, 2022 - Learn to use the if-else conditions logic using Java Stream API to filter the items from a collection based on certain conditions. The 'if-else' condition can be applied as a lambda expression in forEach() function in form of a Consumer action.
🌐
Baeldung
baeldung.com › home › java › java streams › how to use if/else logic in java streams
How to Use if/else Logic in Java Streams | Baeldung
May 28, 2024 - Our forEach method contains if/else logic that verifies whether the Integer is an odd or even number using the Java modulus operator.
Top answer
1 of 2
13

You can write, given for instance a List<Boolean>:

if (!list.stream().allMatch(x -> x)) {
    // not every member is true
}

Or:

if (list.stream().anyMatch(x -> !x)) {
    // at least one member is false
}

If you have an array of booleans, then use Arrays.stream() to obtain a stream out of it instead.


More generally, for a Stream providing elements of (generic) type X, you have to provide a Predicate<? super X> to .{all,any}Match() (either a "full" predicate, or a lambda, or a method reference -- many things go). The return value of these methods are self explanatory -- I think.


Now, to count elements which obey a certain predicate, you have .count(), which you can combine with .filter() -- which also takes (whatever is) a Predicate as an argument. For instance checking if you have more than 2 elements in a List<String> whose length is greater than 5 you'd do:

if (list.stream().filter(s -> s.length() > 5).count() > 2L) {
    // Yup...
}
2 of 2
4

Your problem

Your current problem is that you use directly a lambda expression. Lambdas are instances of functional interfaces. Your lambda does not have the boolean type, that's why your if does not accept it.

This special case's solution

You can use a stream from your collections of booleans here.

if (bools.stream().allMatch((Boolean b)->b)) {
    // do something
}

It is actually much more powerful than this, but this does the trick I believe.

General hint

Basically, since you want an if condition, you want a boolean result. Since your result depends on a collection, you can use Java 8 streams on collections.

Java 8 streams allow you to do many operations on a collection, and finish with a terminal operation. You can do whatever complicated stuff you want with Stream's non-terminal operations. In the end you need one of 2 things:

  • use a terminal operation that returns a boolean (such as allMatch, anyMatch...), and you're done
  • use any terminal operation, but use it in a boolean expression, such as myStream.filter(...).limit(...).count() > 2

You should have a look at your possibilities in this Stream documentation or this one.

🌐
Programiz
programiz.com › java-programming › lambda-expression
Java Lambda Expressions (With Examples)
In Java, the lambda body is of two types. ... This type of lambda body is known as the expression body. ... This type of the lambda body is known as a block body. The block body allows the lambda body to include multiple statements. These statements are enclosed inside the braces and you have to add a semi-colon after the braces. Note: For the block body, you can have a return statement if the body returns a value.
🌐
GeeksforGeeks
geeksforgeeks.org › java › lambda-expressions-java-8
Java Lambda Expressions - GeeksforGeeks
This is a zero-parameter lambda expression! ... It is not mandatory to use parentheses if the type of that variable can be inferred from the context. Parentheses are optional if the compiler can infer the parameter type from the functional interface. ... import java.util.ArrayList; public class GFG{ public static void main(String[] args){ ArrayList<Integer> list = new ArrayList<>(); list.add(1); list.add(2); list.add(3); System.out.println("All elements:"); list.forEach(n -> System.out.println(n)); System.out.println("Even elements:"); list.forEach(n -> { if (n % 2 == 0) System.out.println(n); }); } }
Published   3 weeks ago
🌐
Baeldung
baeldung.com › home › java › lambda expressions and functional interfaces: tips and best practices
Lambda Expressions and Functional Interfaces: Tips and Best Practices | Baeldung
December 16, 2023 - This code is legal, as total variable remains “effectively final,” but will the object it references have the same state after execution of the lambda? No! Keep this example as a reminder to avoid code that can cause unexpected mutations. In this article, we explored some of the best practices and pitfalls in Java 8’s lambda expressions and functional interfaces.
🌐
Java Code Geeks
javacodegeeks.com › home › core java
Lambda of Lambda, if/else from an Optional - Java Code Geeks
March 10, 2016 - The second problem is of course the old chestnut that even if you could do that the methods would not be able to throw a checked exception. (Yes you can wrap with a RuntimeException but it is not the prettiest.) The workaround I found was to use the map function as the success case and the orElseGet to return the failure case. In both branches the code returns an instance of ThrowingRunnable by having a lambda return a lambda.
🌐
Medium
medium.com › @bubu.tripathy › effective-lambda-expressions-in-java-2d4061dde77a
Effective Lambda Expressions in Java | by Bubu Tripathy | Medium
March 11, 2023 - The Lambda expression takes two arguments as input: an accumulator and an element from the collection. The accumulator is the result of the previous operation, or an initial value if this is the first operation.
🌐
GeeksforGeeks
geeksforgeeks.org › java › block-lambda-expressions-in-java
Block Lambda Expressions in Java - GeeksforGeeks
July 23, 2025 - This includes variables, loops, conditional statements like if, else and switch statements, nested blocks, etc. This is created by enclosing the block of statements in lambda body within braces {}. This can even have a return statement i.e return value. ... Now first let us do understand the Lambda expression to get to know about the block lambda expression. ... In this case, lambda may need more than a single expression in its lambda body. Java supports Expression Lambdas which contains blocks of code with more than one statement.
🌐
Medium
medium.com › @marcelogdomingues › java-lambda-expressions-techniques-for-advanced-developersava-lambda-expressions-techniques-for-c1d71c30bb1f
Java Lambda Expressions: Techniques for Advanced Developersava Lambda Expressions: Techniques for…
June 21, 2024 - If the body is a single expression, the return keyword and curly braces can be omitted. ... Before lambda expressions, implementing functional interfaces required creating anonymous inner classes. This approach often led to verbose and less readable code. Example: Sorting a List Using an Anonymous Inner Class · import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; public class TraditionalExample { public static void main(String[] args) { List<String> names = Arrays.asList("John", "Jane", "Jack", "Jill"); Collections.sort(names, new Comparator<String>() { @Override public int compare(String a, String b) { return a.compareTo(b); } }); for (String name : names) { System.out.println(name); } } }
🌐
DZone
dzone.com › coding › java › java 8: lambda functions—usage and examples
Java 8: Lambda Functions—Usage and Examples
May 4, 2016 - Some examples of valid lambda expressions (assuming that relevant functional interfaces are available): (int x) -> x + x x -> x % x () -> 7 (int arg1, int arg2) -> (arg1 + arg2) / (arg1 – arg2) ... -> 7 // if there are no parameters, then empty parentheses () must be provided (arg1, int arg2) -> arg1 / arg2 // if argument types are provided, then it should be provided for all arguments or none of them