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"}]
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.
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.
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.
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“.
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With