Java 8 lambda get and remove element from list

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

    I'm sure this will be an unpopular answer, but it works...

    ProducerDTO[] p = new ProducerDTO[1];
    producersProcedureActive
                .stream()
                .filter(producer -> producer.getPod().equals(pod))
                .findFirst()
                .ifPresent(producer -> {producersProcedureActive.remove(producer); p[0] = producer;}
    

    p[0] will either hold the found element or be null.

    The "trick" here is circumventing the "effectively final" problem by using an array reference that is effectively final, but setting its first element.

提交回复
热议问题