Java 8 lambda get and remove element from list

后端 未结 12 1608
说谎
说谎 2020-12-08 12:47

Given a list of elements, I want to get the element with a given property and remove it from the list. The best solution I found is:

Produce         


        
12条回答
  •  不知归路
    2020-12-08 13:23

    Consider using vanilla java iterators to perform the task:

    public static  T findAndRemoveFirst(Iterable collection, Predicate test) {
        T value = null;
        for (Iterator it = collection.iterator(); it.hasNext();)
            if (test.test(value = it.next())) {
                it.remove();
                return value;
            }
        return null;
    }
    

    Advantages:

    1. It is plain and obvious.
    2. It traverses only once and only up to the matching element.
    3. You can do it on any Iterable even without stream() support (at least those implementing remove() on their iterator).

    Disadvantages:

    1. You cannot do it in place as a single expression (auxiliary method or variable required)

    As for the

    Is it possible to combine get and remove in a lambda expression?

    other answers clearly show that it is possible, but you should be aware of

    1. Search and removal may traverse the list twice
    2. ConcurrentModificationException may be thrown when removing element from the list being iterated

提交回复
热议问题