Java / guava - collect deleted items from iterables

Is there a more elegant way in Guava to remove elements that match a certain predicate from a collection and collect those removed elements at the same time? See the code below.

public static void main(String[] a) {
    final List<String> list = new LinkedList<String>();

    list.add("...");
    ...

    final List<String> removedItems = new LinkedList<String>();

    Iterables.removeIf(list, new Predicate<String>() {
        public boolean apply(final String o) {
            if (...) { // some condition
                removedItems.add(o);
                return true;
            }
            return false;
        }
    });

    System.out.println(removedItems);
}

      

Thank!

edit: My question is not about splitting a list, but about removing items from a collection and collecting them at the same time. I edited my question to avoid confusion.

+3


source to share


2 answers


Predicate<Integer> predicate = new Predicate<>() {
    public boolean apply(final Integer o) {
        return o <= 5;
    }
};

List<Integer> removed = Lists.newLinkedList(Iterables.filter(list, predicate));
Iterables.removeIf(list, predicate);

      



+1


source


Collection.add()

returns true if the call add()

changes the collection. So, you can expand the branch if

/ else

like this:

Iterables.removeIf(list, new Predicate<Integer>() {
    public boolean apply(final Integer o) {
        return o <= 5 && removedItems.add(o);
    }
});

      

With Java 8, this becomes

Iterables.removeIf(list, o -> o <= 5 && removedItems.add(o));

      

... or even (without Guava):



list.removeIf(o -> o <= 5 && removedItems.add(o));

      

Of course not sure if this would be perceived as more readable :-)

Splitting a collection into a predicate:

This question here addresses the issue from a different angle:

Library method for splitting a collection into a predicate

0


source







All Articles