Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stream the removed items in java removeIf?

Tags:

java

java-8

I'm using removeIf to remove certain objects from a list if their name or code is null:

tables.removeIf(t -> ((t.getName() == null) || (t.getCode() == null)));

Is there a way I can get the actual items t that have been removed here? Maybe a list of the removed items, or better yet, a stream of the removed items?

Thanks

like image 544
Jack_Frost Avatar asked Oct 20 '20 16:10

Jack_Frost


People also ask

How do you reuse a stream in Java?

From the documentation: A stream should be operated on (invoking an intermediate or terminal stream operation) only once. A stream implementation may throw IllegalStateException if it detects that the stream is being reused. So the answer is no, streams are not meant to be reused.

What does stream of () method in Java?

Stream of(T t) returns a sequential Stream containing a single element. Parameters: This method accepts a mandatory parameter t which is the single element in the Stream. Return Value: Stream of(T t) returns a sequential Stream containing the single specified element.

How do you stream a collection in Java?

Introduced in Java 8, the Stream API is used to process collections of objects. A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result. A stream is not a data structure instead it takes input from the Collections, Arrays or I/O channels.


2 Answers

You can partition by your criterion and then use the result for whatever you want:

Map<Boolean, List<MyClass>> split = tables.stream()
     .collect(Collectors.partitioningBy(t -> 
                t.getName() == null || t.getCode() == null));

List<MyClass> cleanList = split.get(Boolean.FALSE);
List<MyClass> removedList = split.get(Boolean.TRUE);

cleanList contains what tables would have contained after removeIf, and removedList data that was discarded (the one you were looking for)

like image 119
ernest_k Avatar answered Oct 08 '22 05:10

ernest_k


What about make it in two steps :

find objects you want to remove:

List<ObjectName> toBeRemoved = tables.stream()
        .filter(t -> t.getName() == null || t.getCode() == null)
        .collect(Collectors.toList());

and then remove them from the list :

tables.removeAll(toBeRemoved);
like image 40
YCF_L Avatar answered Oct 08 '22 03:10

YCF_L