Just put the condition into the lambda itself, e.g.

animalMap.entrySet().stream()
        .forEach(
                pair -> {
                    if (pair.getValue() != null) {
                        myMap.put(pair.getKey(), pair.getValue());
                    } else {
                        myList.add(pair.getKey());
                    }
                }
        );

This can be simplified and made more readable using Map.forEach, as suggested by Jorn Vernee:

animalMap.forEach(
        (key, value) -> {
            if (value != null) {
                myMap.put(key, value);
            } else {
                myList.add(key);
            }
        }
);

Of course, these solutions assume that both collections (myMap and myList) are declared and initialized prior to the above pieces of code.

Answer from Alex Shesterov on Stack Overflow
🌐
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 - In this quick article, we’ve explored how to create a Java 8 Stream and how to implement if/else logic using the forEach() method.
Top answer
1 of 5
122

Just put the condition into the lambda itself, e.g.

animalMap.entrySet().stream()
        .forEach(
                pair -> {
                    if (pair.getValue() != null) {
                        myMap.put(pair.getKey(), pair.getValue());
                    } else {
                        myList.add(pair.getKey());
                    }
                }
        );

This can be simplified and made more readable using Map.forEach, as suggested by Jorn Vernee:

animalMap.forEach(
        (key, value) -> {
            if (value != null) {
                myMap.put(key, value);
            } else {
                myList.add(key);
            }
        }
);

Of course, these solutions assume that both collections (myMap and myList) are declared and initialized prior to the above pieces of code.

2 of 5
18

In most cases, when you find yourself using forEach on a Stream, you should rethink whether you are using the right tool for your job or whether you are using it the right way.

Generally, you should look for an appropriate terminal operation doing what you want to achieve or for an appropriate Collector. Now, there are Collectors for producing Maps and Lists, but no out of-the-box collector for combining two different collectors, based on a predicate.

Now, this answer contains a collector for combining two collectors. Using this collector, you can achieve the task as

Pair<Map<KeyType, Animal>, List<KeyType>> pair = animalMap.entrySet().stream()
    .collect(conditional(entry -> entry.getValue() != null,
            Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue),
            Collectors.mapping(Map.Entry::getKey, Collectors.toList()) ));
Map<KeyType,Animal> myMap = pair.a;
List<KeyType> myList = pair.b;

But maybe, you can solve this specific task in a simpler way. One of you results matches the input type; it’s the same map just stripped off the entries which map to null. If your original map is mutable and you don’t need it afterwards, you can just collect the list and remove these keys from the original map as they are mutually exclusive:

List<KeyType> myList=animalMap.entrySet().stream()
    .filter(pair -> pair.getValue() == null)
    .map(Map.Entry::getKey)
    .collect(Collectors.toList());

animalMap.keySet().removeAll(myList);

Note that you can remove mappings to null even without having the list of the other keys:

animalMap.values().removeIf(Objects::isNull);

or

animalMap.values().removeAll(Collections.singleton(null));

If you can’t (or don’t want to) modify the original map, there is still a solution without a custom collector. As hinted in Alexis C.’s answer, partitioningBy is going into the right direction, but you may simplify it:

Map<Boolean,Map<KeyType,Animal>> tmp = animalMap.entrySet().stream()
    .collect(Collectors.partitioningBy(pair -> pair.getValue() != null,
                 Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)));
Map<KeyType,Animal> myMap = tmp.get(true);
List<KeyType> myList = new ArrayList<>(tmp.get(false).keySet());

The bottom line is, don’t forget about ordinary Collection operations, you don’t have to do everything with the new Stream API.

🌐
HowToDoInJava
howtodoinjava.com › home › java 8 › using ‘if-else’ conditions with java streams
Using 'if-else' Conditions with Java Streams - HowToDoInJava
March 3, 2022 - The if-else condition can be applied using the lambda expressions in stream filter() function. ... Learn to use the if-else conditions logic using Java Stream API to filter the items from a collection based on certain conditions.
🌐
Medium
medium.com › @mohitbajaj1995 › how-to-use-if-else-logic-in-java-streams-10-practical-approaches-956ca65ade3c
How to use If/else Logic in Java Streams: 10 Practical Approaches | by Mohit Bajaj | Medium
March 6, 2025 - This is the simplest way to start — just put your if/else logic directly inside forEach(): List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); numbers.stream() .forEach(num -> { if (num % 2 == 0) { System.out.println(num ...
🌐
Javaprogramto
javaprogramto.com › 2021 › 12 › java-8-streams-if-else.html
Java 8 Streams if else logic JavaProgramTo.com
December 11, 2021 - In java 8, stream api is added with the forEach() method and inside this, we can add the if-else conditions.
🌐
Shootskill
shootskill.com › java8 › stream-if-else-logic
Shootskill
We cannot provide a description for this page right now
Find elsewhere
🌐
Medium
medium.com › @prawin609 › replacing-nested-if-else-null-checks-with-optional-map-and-filter-in-java-streams-api-6d831fbd81ca
Replacing Nested If-Else Null Checks with Optional, Map, and Filter in Java Streams API | by Prawin Thangaswamy | Medium
September 8, 2024 - Nested if-else statements, especially when used for null checks, can lead to code that is difficult to read, maintain, and debug. Java's Optional class, along with map, filter, and other stream operations, provides a cleaner and more readable alternative for handling such scenarios.
🌐
YouTube
youtube.com › ocean of code
5 mins || Java 8 Stream API if else logic || Easy Way - YouTube
In this video, we have talked about, How to write conditional statements like if, else while iterating through Collections Data Structure using Stream API. P...
Published: March 28, 2020
Views: 416
🌐
Coderanch
coderanch.com › t › 649697 › java › Java-streams-Filter
Java 8 streams - Filter if else not (Features new in Java 8 forum at Coderanch)
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums · this forum made possible by our volunteer staff, including ... ... Hi, I'm trying to figure out if there's a more elegant way of doing this with streams rather than checking separately through an if-else statement?
🌐
CodingTechRoom
codingtechroom.com › tutorial › java-java-8-streams-if-else-logic
Mastering Java 8 Streams: Implementing If-Else Logic Effectively - CodingTechRoom
Combine multiple conditions in your Stream operations using if-else with method references for better readability.
🌐
Stack Overflow
stackoverflow.com › questions › 56129465 › how-to-use-if-else-statements-with-stream-classes
java - How to use IF ELSE statements with stream classes? - Stack Overflow
This is a Client-Server GUI Application, here I want to send and receive messages between them. the condition is , when the client send "Hello" to server , the server only reply with this message "Hello Client, I am server". so, how can I use if else in this case?
🌐
Medium
terricksolo.medium.com › functional-programming-in-java-replace-traditional-if-else-blocks-with-maps-and-streams-8901bac92e5e
Functional programming in Java — Replace traditional if-else blocks with Maps and Streams | by Prince Solomon S | Medium
May 14, 2021 - Lengthy if-else blocks are developers nightmare and hard to maintain with full of side effects.Sonar rightly flags such code blocks as ‘Cognitive complexities’. Yes, it is. Introduction of Functional interface in Java 8 paved way for first-class functions.This is very useful when paired with predicates to replace traditional if-else blocks
Top answer
1 of 2
3

If at least one of the values is guaranteed, you could refactor it like this:

public List<UserAction> getUserActionList(Map<String, String> map) {
    return Stream.of("userid", "username", "userrole")
        .map(map::get)
        .filter(s -> !checkForNullEmpty(s))
        .limit(1)
        .map(output -> new UserAction(map, output))
        .collect(Collectors.toList());
}

If it is not guaranteed that at least one value will be non-null, it's a little uglier, but not too bad:

public List<UserAction> getUserActionList(Map<String, String> map) {
    return Stream.of("userid", "username", "userrole")
        .map(map::get)
        .filter(s -> !checkForNullEmpty(s))
        .limit(1)
        .map(output -> new UserAction(map, output))
        .map(Collections::singletonList)
        .findFirst()
        .orElseGet(() -> Arrays.asList(new UserAction(map, null)));
}
2 of 2
2

It's not really clear about the task you need to accomplish, but in general, everything that you need to write in your if statements you can do with filter() method from Stream API. Then, in map() method you'd have the exact logic which is needed to be done with the data (e.g. transforming it to some other type or getting values which are needed). collect() method is used to create a result from the Stream, e.g. list, set, map, single object or anything else. For example:

map.entrySet().stream()
                .filter(e -> {
                    // filter the data here, so if isStrOrInt or containsUserData is false - we will not have it in map() method
                    boolean isStrOrInt = e.getValue() instanceof String || e.getValue() instanceof Integer;
                    boolean containsUserData = e.getKey().contains("userrole") || e.getKey().contains("userid") || e.getKey().contains("username");
                    return isStrOrInt && containsUserData;
                })
                .map(e -> {
                    if (e.getKey().contains("userrole")) {
                        // do something
                    }
                    // some more logic here
                    return e.getValue();
                })
                .collect(Collectors.toList());
                // or e.g. .reduce((value1, value2) -> value1 + value2);

If you need to create a single object in the end, you would probably need reduce() method. I recommend you to check reduction operations, general information about Stream API to understand how they work.

🌐
Stack Overflow
stackoverflow.com › questions › 36524745 › if-else-in-stream-filter-java
if-else in stream filter java - Stack Overflow
So I converted the if else like so. CopyfilteredList = classABCList.stream() .filter(abc ->(abc.getName() == "ABC" && abc.before(timestamp1)) || abc.before(timestamp2) ).collect(toList()); Here is an ideone example suggested by RadioDef(Thanks for the example!) ... Sign up to request clarification or add additional context in comments.