Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java8 Stream : Collect elements after a condition is met

My POJO is as follows

class EventUser {   private id;   private userId;   private eventId; } 

I retrieve EventUser object as follows:

List<EventUser> eventUsers = eventUserRepository.findByUserId(userId); 

Say the 'eventUsers' is as follows:

[ {"id":"id200","userId":"001","eventId":"1010"}, {"id":"id101","userId":"001","eventId":"4212"}, {"id":"id402","userId":"001","eventId":"1221"}, {"id":"id301","userId":"001","eventId":"2423"}, {"id":"id701","userId":"001","eventId":"5423"}, {"id":"id601","userId":"001","eventId":"7423"} ] 

Using streaming, and without using any intermediate variable , how can I filter and collect events after a given EventUser.id: ex:

List<EventUser> filteredByOffSet = eventUsers.stream.SOMEFILTER_AND_COLLECT("id301"); 

the result should be :

[{"id":"id301","userId":"001","eventId":"2423"}, {"id":"id701","userId":"001","eventId":"5423"}, {"id":"id601","userId":"001","eventId":"7423"}] 
like image 672
Ashika Umanga Umagiliya Avatar asked Sep 11 '18 05:09

Ashika Umanga Umagiliya


People also ask

Does Java stream collect preserve order?

If our Stream is ordered, it doesn't matter whether our data is being processed sequentially or in parallel; the implementation will maintain the encounter order of the Stream.

What are the disadvantages of using java8 if any?

Default Methods are distracting Default methods enable a default implementation of a function in the interface itself. This is definitely one of the coolest new features Java 8 brings to the table but it somewhat interferes with the way we used to do things.

What is the correct difference between collection and stream in Java 8?

Streams are not modifiable i.e one can't add or remove elements from streams. These are modifiable i.e one can easily add to or remove elements from collections. Streams are iterated internally by just mentioning the operations. Collections are iterated externally using loops.

What is peek in java8?

peek()'s Javadoc page says: “This method exists mainly to support debugging, where you want to see the elements as they flow past a certain point in a pipeline“.


1 Answers

In Java 8 you need a stateful filter

public static <T> Predicate<T> from(Predicate<T> test) {     boolean[] found = { false };     // once found, always true     return t -> found[0] || (found[0] = test.test(t)); } 

NOTE: this only makes sense for single threaded streams.

List<EventUser> filteredByOffSet =       eventUsers.stream()                .filter(from(e -> "id301".equals(e.getId()))                .collect(Collectors.toList()); 
like image 80
Peter Lawrey Avatar answered Oct 21 '22 16:10

Peter Lawrey