java - Java 8 Stream - 在特定项目最后出现后获取项目
问题描述
我想在列表中最后一次出现特定项目后获取该项目。例如
List<Bean> list = ArrayList<Bean>() {{
add(new Bean(1, null)); // null
add(new Bean(2, "text2"));
add(new Bean(3, "text3"));
add(new Bean(4, "text4"));
add(new Bean(5, null)); // null last occurence
add(new Bean(6, "text6"); // want this one.
}}
我想在最后一次出现空文本后Bean
获取该项目,例如上面的 Bean id 6。
非常感谢。
解决方案
正如评论中提到的,Streams 不是这个任务的好解决方案。但是仍然可以使用它们来处理它们Atomic
:
AtomicBoolean isPreviousNull = new AtomicBoolean(false);
AtomicReference<Bean> lastOccurrence = new AtomicReference<>(null);
list.forEach(item -> {
if (item.text == null) {
isPreviousNull.set(true);
} else if (isPreviousNull.get()) {
isPreviousNull.set(false);
lastOccurrence.set(item);
}
});
System.out.println(lastOccurrence.get());
推荐阅读
- ios - AFNetworking 3.0 AFHTTPSessionManager 使用 NSURLRequest
- html - 如何并排制作带有图像和文本的部分
- java - Spring Boot,在 REST 响应中将日期时间精度定义为毫秒
- javascript - Javascript循环以错误的顺序执行
- java - 在 LinearLayout 中以相反的顺序添加视图
- javascript - 如何在反应中强制重新加载和清除最近更新的缓存
- mysql - .Net 连接字符串连接 MySQL localhost 没有密码
- python - 如何绘制熊猫数据框的每一列?
- yql - 通过 HTTP POST 和 PUT 方法批量插入/更新 Vespa 文档
- reactjs - FontAwesome SCSS Tree-Shaking