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
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.
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.
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.
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)
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);
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