Java 8 stream api is very nice feature and I absolutely like it. One thing that get's on my nerves is that 90% of the time I want to have input as a collection and output as collections. The consequence is I have to call stream()
and collect()
method all the time:
collection.stream().filter(p->p.isCorrect()).collect(Collectors.toList());
Is there any java api that would let me skip the stream and directly operate on collections (like linq
in c#?):
collection.filter(p->p.isCorrect)
Yes, using Collection#removeIf(Predicate)
:
Removes all of the elements of this collection that satisfy the given predicate.
Note that it will change the given collection, not return a new one. But you can create a copy of the collection and modify that. Also note that the predicate needs to be negated to act as a filter:
public static <E> Collection<E> getFilteredCollection(Collection<E> unfiltered, Predicate<? super E> filter) { List<E> copyList = new ArrayList<>(unfiltered); // removeIf takes the negation of filter copyList.removeIf(e -> { return !filter.test(e);}); return copyList; }
But as @Holger suggests in the comments, if you choose to define this utility method in your code and use it everywhere you need to get a filtered collection, then just delegate the call to the collect
method in that utility. Your caller code will then be more concise.
public static <E> Collection<E> getFilteredCollection(Collection<E> unfiltered, Predicate<? super E> filter) { return unfiltered.stream() .filter(filter) .collect(Collectors.toList()); }
You might like using StreamEx
StreamEx.of(collection).filter(PClass::isCorrect).toList();
This has the advantages of being slightly more brief while keeping immutability.
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