Java 8 lambda get and remove element from list

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

    Combining my initial idea and your answers I reached what seems to be the solution to my own question:

    public ProducerDTO findAndRemove(String pod) {
        ProducerDTO p = null;
        try {
            p = IntStream.range(0, producersProcedureActive.size())
                 .filter(i -> producersProcedureActive.get(i).getPod().equals(pod))
                 .boxed()
                 .findFirst()
                 .map(i -> producersProcedureActive.remove((int)i))
                 .get();
            logger.debug(p);
        } catch (NoSuchElementException e) {
            logger.error("No producer found with POD [" + pod + "]");
        }
        return p;
    }
    

    It lets remove the object using remove(int) that do not traverse again the list (as suggested by @Tunaki) and it lets return the removed object to the function caller.

    I read your answers that suggest me to choose safe methods like ifPresent instead of get but I do not find a way to use them in this scenario.

    Are there any important drawback in this kind of solution?

    Edit following @Holger advice

    This should be the function I needed

    public ProducerDTO findAndRemove(String pod) {
        return IntStream.range(0, producersProcedureActive.size())
                .filter(i -> producersProcedureActive.get(i).getPod().equals(pod))      
                .boxed()                                                                
                .findFirst()
                .map(i -> producersProcedureActive.remove((int)i))
                .orElseGet(() -> {
                    logger.error("No producer found with POD [" + pod + "]"); 
                    return null; 
                });
    }
    

提交回复
热议问题