Remove null values in ArrayList


  • By Using Collections.singleton(null) we can remove the null values in the list.



  1. package commonsUtils;

  2. import java.util.ArrayList;
  3. import java.util.Collections;
  4. import java.util.HashSet;
  5. import java.util.List;
  6. import java.util.Set;

  7. public class RemDupList {
  8.      public static void main(String[] args) {
  9. // TODO Auto-generated method stub
  10. List<String> arrayList1 = new ArrayList<String>();

  11.    arrayList1.add("A");
  12.    arrayList1.add("A");
  13.    arrayList1.add("B");
  14.    arrayList1.add("B");
  15.    arrayList1.add("B");
  16.    arrayList1.add("C");
  17.    arrayList1.add(null);
  18.    arrayList1.add(null);
  19.    for (String item : arrayList1){
  20.      System.out.println(item);
  21.    }
  22.    HashSet<String> hashSet = new HashSet<String>(arrayList1);

  23.             arrayList1 = new ArrayList<String>(hashSet);
  24.    System.out.println(" =============== ");
  25.     arrayList1 .removeAll(Collections.singleton(null)); //This will remove the null values
  26.     arrayList1 .removeAll(Collections.singleton("A")); //This will remove the value "A" in the entire list.
  27.    for (String item : arrayList1 ){
  28.      System.out.println(item);
  29.    }
  30.     }
  31. }

 Output : 
  Before Removing null values
 A
 A
 B
 B
 B
 C
 null
 null
 =============== 
 After Removing null values
 B
 C

No comments:

Post a Comment