【问题标题】:Collect a stream after an objects attribute exceeds a certain threshold在对象属性超过某个阈值后收集流
【发布时间】:2020-12-03 19:31:40
【问题描述】:

假设我有一个自定义对象列表MaDate,其中的字段temp 类型为int。我想在第一个达到某个阈值MaDate.temp >= 10 后使用流来获取所有项目。

class MaDate {
    int temp;
    // some other fields
    MaDate(int temp){
       this.temp = temp;
    }
    int getTemp(){
        return temp;
    }
}

 List<MaDate> myList = new ArrayList<>();
 myList.add(new MaDate(3));
 myList.add(new MaDate(7));
 myList.add(new MaDate(8));
 myList.add(new MaDate(4));
 myList.add(new MaDate(10));
 myList.add(new MaDate(3));
 myList.add(new MaDate(9));

理想情况下,结果列表应包含具有temp 值 [10,3,9] 的最后 3 个元素。

我不能使用filter

myList.stream().filter(m -> m.getTemp() >= 10)...

因为这会消除所有价值低于 10 的对象。我也不能使用skip

myList.stream().skip(4)...

因为我事先不知道索引。我不能用

findFirst(m -> m.getTemp() >= 10)

因为一旦达到阈值后我需要所有对象,无论对象在那之后具有哪些值。

我能否以某种方式将上述内容组合起来以获得我想要的内容或编写我自己的方法以放入 skipfilter

 myList.stream().skip(**as long as treshold not met**)

 myList.stream().filter(**all elements after first element value above 10**)

?

【问题讨论】:

    标签: java filter java-8 java-stream skip


    【解决方案1】:

    如果我正确理解您的问题,那么您可以使用Stream#dropWhile(Predicate)

    如果此流是有序的,则返回一个流,该流由该流的剩余元素在删除与给定谓词匹配的元素的最长前缀之后组成。否则,如果此流是无序的,则在删除与给定谓词匹配的元素子集后,返回由该流的剩余元素组成的流。

    例子:

    List<MaDate> originalList = ...;
    List<MaDate> newList = originalList.stream()
            .dropWhile(m -> m.getTemp() < 10)
            .collect(Collectors.toList());
    

    请注意,dropWhile 是在 Java 9 中添加的。如果您使用的是 Java 8,此问答显示了一种解决方法:Limit a stream by a predicate

    【讨论】:

    • 非常感谢。正是我需要的。
    猜你喜欢
    • 2020-07-21
    • 2011-09-16
    • 1970-01-01
    • 1970-01-01
    • 2020-03-23
    • 1970-01-01
    • 1970-01-01
    • 2013-02-28
    • 1970-01-01
    相关资源
    最近更新 更多