Sunday, 13 March 2011

How to Convert an ArrayList to a HashSet?

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class ArrayListToHashSet {

public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add(null);
list.add("A");
list.add("B");
Set<String> hashset = new HashSet<String>(list);
list = new ArrayList<String>(hashset);
System.out.println(list.toString());
}
}

The above code example also can be used to remove duplicate items from an ArrayList.

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class ArrayListToHashSet {

public static void main(String[] args) {
List list = new ArrayList();
list.add(null);
list.add("A");
list.add("A");
list.add("A");
list.add("A");
list.add("B");
list.add("B");
list.add("B");
list.add("C");
Set hashset = new HashSet(list);
list = new ArrayList(hashset);
System.out.println(list.toString());
}

}

No comments:

Post a Comment