Java 8 lambda get and remove element from list

We Are Going To Discuss About Java 8 lambda get and remove element from list. So lets Start this Java Article.

Java 8 lambda get and remove element from list

Advertisements
  1. Java 8 lambda get and remove element from list

    To Remove element from the list
    objectA.removeIf(x -> conditions);
    eg:
    objectA.removeIf(x -> blockedWorkerIds.contains(x));

  2. Java 8 lambda get and remove element from list

    To Remove element from the list
    objectA.removeIf(x -> conditions);
    eg:
    objectA.removeIf(x -> blockedWorkerIds.contains(x));

Solution 1

Advertisements

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

Original Author uma shankar Of This Content

Solution 2

Advertisements

Use can use filter of Java 8, and create another list if you don’t want to change the old list:

List<ProducerDTO> result = producersProcedureActive
                            .stream()
                            .filter(producer -> producer.getPod().equals(pod))
                            .collect(Collectors.toList());

Original Author Toi Nguyen Of This Content

Solution 3

Advertisements

The below logic is the solution without modifying the original list

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");

List<String> str3 = str1.stream()
                        .filter(item -> !str2.contains(item))
                        .collect(Collectors.toList());

str1 // ["A", "B", "C", "D"]
str2 // ["D", "E"]
str3 // ["A", "B", "C"]

Original Author KimchiMan Of This Content

Solution 4

Advertisements

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.

Original Author asifsid88 Of This Content

Conclusion

So This is all About This Tutorial. Hope This Tutorial Helped You. Thank You.

Also Read,

Siddharth

I am an Information Technology Engineer. I have Completed my MCA And I have 4 Year Plus Experience, I am a web developer with knowledge of multiple back-end platforms Like PHP, Node.js, Python and frontend JavaScript frameworks Like Angular, React, and Vue.

Leave a Comment