Java 9 ArrayList removeAll except some

Method retain() of ArrayList class can be used if you want to clear all elements except some:

values.retainAll(exceptions);

You can check also:

Clear ArrayList except some items

If you want to clear ArrayList except several values you can use method retain:

import java.util.ArrayList;

ArrayList<String> list = new ArrayList<>();
list.add("Java");
list.add("Python");
list.add("Javascript");
list.add("Perl");
list.add("C#");
list.add("C++");
list.add("Groovy");
System.out.println("list: " + list);

ArrayList<String> exceptions = new ArrayList<>();
exceptions.add("Python");
exceptions.add("Java");
exceptions.add("Groovy");
System.out.println("exceptions: " + exceptions);

list.retainAll(exceptions);
System.out.println("left: " + list);

result:

list: [Java, Python, Javascript, Perl, C#, C++, Groovy]
exceptions: [Python, Java, Groovy]
left: [Java, Python, Groovy]

Share Tweet Send
0 Comments
Loading...