首页 > 解决方案 > 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。

非常感谢。

标签: javajava-stream

解决方案


正如评论中提到的,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());

推荐阅读