I was playing around with Java 8 lambdas to easily filter collections. But I did not find a concise way to retrieve the result as a new list within the same statement. Here is my most concise approach so far:

List<Long> sourceLongList = Arrays.asList(1L, 10L, 50L, 80L, 100L, 120L, 133L, 333L);
List<Long> targetLongList = new ArrayList<>();
sourceLongList.stream().filter(l -> l > 100).forEach(targetLongList::add);

Examples on the net did not answer my question because they stop without generating a new result list. There must be a more concise way. I would have expected, that the Stream class has methods as toList(), toSet(), …

Is there a way that the variables targetLongList can be directly be assigned by the third line?

推荐答案

What you are doing may be the simplest way, provided your stream stays sequential—otherwise you will have to put a call to sequential() before forEach.

[later edit: the reason the call to sequential() is necessary is that the code as it stands (forEach(targetLongList::add)) would be racy if the stream was parallel. Even then, it will not achieve the effect intended, as forEach is explicitly nondeterministic—even in a sequential stream the order of element processing is not guaranteed. You would have to use forEachOrdered to ensure correct ordering. The intention of the Stream API designers is that you will use collector in this situation, as below.]

An alternative is

targetLongList = sourceLongList.stream()
    .filter(l -> l > 100)
    .collect(Collectors.toList());

Java相关问答推荐

Java模式匹配记录

有关手动创建的包的问题

需要一个找不到的jakarta.sistence.EntityManager类型的Bean

在JavaFX项目中注册组合框的控件FX验证器时,模块系统出错

呈现文本和四舍五入矩形时出现的JavaFX窗格白色瑕疵

当Volatile关键字真的是必要的时候?

在Frege中,我如何将一个字符串安全地转换为一个可能的Int?

Java Telnet客户端重复的IAC符号

为什么有两种实现来检索数组类的组件类型?

Android Studio模拟器没有互联网

寻找Thread.sky()方法的清晰度

在使用具有不同成本的谓词调用allMatch之前对Java流进行排序会带来什么好处吗?

在打开搜索结果时,如何让Eclipse打开整个文件?

在整数列表中查找和可被第三个整数整除的对时出现无法解释的RunTimeError

本机方法(JNI)总是编译的吗?

如何在Spring Boot中为不同的部署环境管理多个.properties文件?

org.springframework.web.HttpRequestMethodNotSupportedException:请求方法';帖子';不支持

由于可为null,无法在kotlin中实现java接口

Spring Integration SFTP 连接失败 - 无法协商 kex 算法的密钥交换

为什么当我输入变量而不是直接输入字符串时,我的方法不起作用?