Removing some values from the List in Java Example
Remove one List value from another list:
Java Program to Remove List Values from another List values:
In this program we are deleting the list2 values from list1.
[java gutter=”false”]
package in.javadomain;
import java.util.ArrayList;
import java.util.List;
public class RemoveListValue {
public static void main(String[] args) {
List<String> myList1 = new ArrayList<String>();
myList1.add("Java");
myList1.add("PHP");
myList1.add("C");
List<String> myList2 = new ArrayList<String>();
myList2.add("Java");
myList2.add("PHP");
System.out.println("List 1 Values before removing");
for (String list1Val : myList1) {
System.out.println(list1Val);
}
myList1.removeAll(myList2);
System.out.println("List 1 Values after removing");
for (String list1Val : myList1) {
System.out.println(list1Val);
}
}
}
[/java]
Output:
[plain gutter=”false”]
List 1 Values before removing
Java
PHP
C
List 1 Values after removing
C
[/plain]
Java Program to Remove Some values from List Example:
In this program we are searching “Java” from list1 and adding the value in list2, then using the removeAll function, deleting the list2 value from list1.
[java gutter=”false”]
package in.javadomain;
import java.util.ArrayList;
import java.util.List;
public class RemoveListValue {
public static void main(String[] args) {
List<String> myList1 = new ArrayList<String>();
myList1.add("Java");
myList1.add("PHP");
myList1.add("C");
List<String> myList2 = new ArrayList<String>();
for (String list1Value : myList1) {
if (list1Value.equalsIgnoreCase("Java")) {
myList2.add(list1Value);
}
}
myList1.removeAll(myList2);
System.out.println("List 1 Values after removing");
for (String list1Val : myList1) {
System.out.println(list1Val);
}
}
}
[/java]
Output:
[plain gutter=”false”]
List 1 Values after removing
PHP
C
[/plain]
Recommended Java Books: