Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 - omitting tedious collect method

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) 
like image 359
user3364192 Avatar asked May 09 '16 19:05

user3364192


2 Answers

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()); } 
like image 134
M A Avatar answered Oct 17 '22 10:10

M A


You might like using StreamEx

StreamEx.of(collection).filter(PClass::isCorrect).toList(); 

This has the advantages of being slightly more brief while keeping immutability.

like image 45
GuiSim Avatar answered Oct 17 '22 10:10

GuiSim