Collect a stream after an objects attribute exceeds a certain threshold

Tags: , , , ,



Assume I have a list of custom objects MaDate with a field temp of type int. I want to use streams to get all items after the first hits a certain threshold MaDate.temp >= 10 .

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

And

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

Ideally the result list should contain the last 3 elements having temp values [10,3,9].

I can not use filter

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

because this would eliminate every object with value under 10. And I can not also use skip

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

because I do not know the index beforehand. I can not use

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

because I need all objects after the treshold was reached once regardles which values the objects have after that.

Can I combine those above somehow to get what I want or write my own method to put in skip or filter

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

or

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

?

Answer

If I understand your question correctly then you can use Stream#dropWhile(Predicate):

Returns, if this stream is ordered, a stream consisting of the remaining elements of this stream after dropping the longest prefix of elements that match the given predicate. Otherwise returns, if this stream is unordered, a stream consisting of the remaining elements of this stream after dropping a subset of elements that match the given predicate.

Example:

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

Note that dropWhile was added in Java 9. This Q&A shows a workaround if you’re using Java 8: Limit a stream by a predicate.



Source: stackoverflow