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());
}
}
A java blog with a collection of examples and tutorials on Java and related technologies. (Under maintenance with continuous updates) Be in touch with java jazzle or k2java.blogspot.com.
Sunday, March 13, 2011
How to Convert an ArrayList to a HashSet?
Labels:
ArrayList,
Collections,
conversion,
HashSet,
java,
list,
set
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment