Java 8 lambda get and remove element from list

后端 未结 12 1604
说谎
说谎 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条回答
  •  猫巷女王i
    2020-12-08 13:19

    When we want to get multiple elements from a List into a new list (filter using a predicate) and remove them from the existing list, I could not find a proper answer anywhere.

    Here is how we can do it using Java Streaming API partitioning.

    Map> classifiedElements = producersProcedureActive
        .stream()
        .collect(Collectors.partitioningBy(producer -> producer.getPod().equals(pod)));
    
    // get two new lists 
    List matching = classifiedElements.get(true);
    List nonMatching = classifiedElements.get(false);
    
    // OR get non-matching elements to the existing list
    producersProcedureActive = classifiedElements.get(false);
    

    This way you effectively remove the filtered elements from the original list and add them to a new list.

    Refer the 5.2. Collectors.partitioningBy section of this article.

提交回复
热议问题