- By Using Collections.singleton(null) we can remove the null values in the list.
- package commonsUtils;
- import java.util.ArrayList;
- import java.util.Collections;
- import java.util.HashSet;
- import java.util.List;
- import java.util.Set;
- public class RemDupList {
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- List<String> arrayList1 = new ArrayList<String>();
- arrayList1.add("A");
- arrayList1.add("A");
- arrayList1.add("B");
- arrayList1.add("B");
- arrayList1.add("B");
- arrayList1.add("C");
- arrayList1.add(null);
- arrayList1.add(null);
- for (String item : arrayList1){
- System.out.println(item);
- }
- HashSet<String> hashSet = new HashSet<String>(arrayList1);
- arrayList1 = new ArrayList<String>(hashSet);
- System.out.println(" =============== ");
- arrayList1 .removeAll(Collections.singleton(null)); //This will remove the null values
- arrayList1 .removeAll(Collections.singleton("A")); //This will remove the value "A" in the entire list.
- for (String item : arrayList1 ){
- System.out.println(item);
- }
- }
- }
Output :
Before Removing null values
A
A
B
B
B
C
null
null
===============
After Removing null values
B
C
No comments:
Post a Comment