Java 8 lambda get and remove element from list

后端 未结 12 1611
说谎
说谎 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:17

    The direct solution would be to invoke ifPresent(consumer) on the Optional returned by findFirst(). This consumer will be invoked when the optional is not empty. The benefit also is that it won't throw an exception if the find operation returned an empty optional, like your current code would do; instead, nothing will happen.

    If you want to return the removed value, you can map the Optional to the result of calling remove:

    producersProcedureActive.stream()
                            .filter(producer -> producer.getPod().equals(pod))
                            .findFirst()
                            .map(p -> {
                                producersProcedureActive.remove(p);
                                return p;
                            });
    

    But note that the remove(Object) operation will again traverse the list to find the element to remove. If you have a list with random access, like an ArrayList, it would be better to make a Stream over the indexes of the list and find the first index matching the predicate:

    IntStream.range(0, producersProcedureActive.size())
             .filter(i -> producersProcedureActive.get(i).getPod().equals(pod))
             .boxed()
             .findFirst()
             .map(i -> producersProcedureActive.remove((int) i));
    

    With this solution, the remove(int) operation operates directly on the index.

提交回复
热议问题