Guava - How to remove from a list, based on a predicate, keeping track of what was removed?

Iain picture Iain · Jun 27, 2011 · Viewed 24.4k times · Source

I have an ArrayList to be filtered, and various Guava Predicates to filter it with. This list will have only 50-100 elements.

I was planning on Iterables.removeIf using each predicate in turn. It is perhaps not maximally efficient but never mind (at least removeIf has some optimization for RandomAccess lists)

For debugging, I want to concisely log what each predicate did. e.g.

Pred0 removed [a, c, g]
Pred1 removed []
Pred2 removed [b, f]

There are some obvious hack solutions but what would you suggest as the cleanest?

For bonus points, it should be reasonably efficient too. ;)

Answer

JanRavn picture JanRavn · Jun 27, 2011

I would capture the removed elements in your Predicate code.

List<String> removedElements = Lists.newArrayList();
final Iterables.removeIf(list, new Predicate<String>() {
    @Override
    public boolean apply(String input) {
        if ("a".equals(input)) {
            removedElements.add(input);
            return true;
        }
        return false;
    }
});