Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 lambda get and remove element from list

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:

ProducerDTO p = producersProcedureActive                 .stream()                 .filter(producer -> producer.getPod().equals(pod))                 .findFirst()                 .get(); producersProcedureActive.remove(p); 

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

like image 672
Marco Stramezzi Avatar asked Feb 29 '16 13:02

Marco Stramezzi


People also ask

How do I remove an object from a list based on condition in Java?

To remove elements from ArrayList based on a condition or predicate or filter, use removeIf() method. You can call removeIf() method on the ArrayList, with the predicate (filter) passed as argument. All the elements that satisfy the filter (predicate) will be removed from the ArrayList.

How do you remove a specific item from a collection in Java?

An element can be removed from a Collection using the Iterator method remove(). This method removes the current element in the Collection. If the remove() method is not preceded by the next() method, then the exception IllegalStateException is thrown.

Which method is used to eliminate elements based on criteria?

The 'filter' method is used to eliminate elements based on a criteria.


2 Answers

To Remove element from the list

objectA.removeIf(x -> conditions); 

eg:

objectA.removeIf(x -> blockedWorkerIds.contains(x));  List<String> str1 = new ArrayList<String>(); str1.add("A"); str1.add("B"); str1.add("C"); str1.add("D");  List<String> str2 = new ArrayList<String>(); str2.add("D"); str2.add("E");  str1.removeIf(x -> str2.contains(x));   str1.forEach(System.out::println); 

OUTPUT: A B C

like image 59
uma shankar Avatar answered Sep 28 '22 05:09

uma shankar


Although the thread is quite old, still thought to provide solution - using Java8.

Make the use of removeIf function. Time complexity is O(n)

producersProcedureActive.removeIf(producer -> producer.getPod().equals(pod)); 

API reference: removeIf docs

Assumption: producersProcedureActive is a List

NOTE: With this approach you won't be able to get the hold of the deleted item.

like image 23
asifsid88 Avatar answered Sep 28 '22 07:09

asifsid88