如何在Java 8 stream forEach中使用if-else逻辑 [英] How to use if-else logic in Java 8 stream forEach

查看:5377
本文介绍了如何在Java 8 stream forEach中使用if-else逻辑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要做的是在下面的2个流调用中显示。我想根据某些条件将一个集合拆分为两个新集合。理想情况下我想在1中进行。我已经看到了用于.map函数的条件,但找不到forEach的任何内容。实现我想要的最好方法是什么?

What I want to do is shown below in 2 stream calls. I want to split a collection into 2 new collections based on some condition. Ideally I want to do it in 1. I've seen conditions used for the .map function of streams, but couldn't find anything for the forEach. What is the best way to achieve what I want?

    animalMap.entrySet().stream()
            .filter(pair-> pair.getValue() != null)
            .forEach(pair-> myMap.put(pair.getKey(), pair.getValue()));

    animalMap.entrySet().stream()
            .filter(pair-> pair.getValue() == null)
            .forEach(pair-> myList.add(pair.getKey()));


推荐答案

只需将条件放入lambda本身,例如

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

当然,这假设两个集合( myMap myList )在上面的代码之前声明并初始化。

Of course, this assumes that both collections (myMap and myList) are declared and initialized prior to the above piece of code.

更新:使用 Map.forEach 使代码更短,更有效率和可读性,因为 Jorn Vernee 建议:

Update: using Map.forEach makes the code shorter, plus more efficient and readable, as Jorn Vernee kindly suggested:

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

这篇关于如何在Java 8 stream forEach中使用if-else逻辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆