Jack_Frost
Jack_Frost

Reputation: 229

How to stream the removed items in java removeIf?

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

Upvotes: 5

Views: 1217

Answers (2)

ernest_k
ernest_k

Reputation: 45329

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)

Upvotes: 6

Youcef LAIDANI
Youcef LAIDANI

Reputation: 60036

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

Upvotes: 3

Related Questions