FAQ

Java

JSP

Servlet


Advertisement



How to Convert an ArrayList to a HashSet?

This code example shows how to convert ArrayList to 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());
}

}


Printer-friendly version Printer-friendly version | Send this 
article to a friend Mail this to a friend

Previous Next vertical dots separating previous/next from contents/index/pdf Contents

  |   |