Privacy Policy Terms Of Use. Copyright © 2006-2010 Java Tutorials and Examples.
Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks of their respective owners.
- import java.util.ArrayList;
- import java.util.HashSet;
- //Java ArrayList to Set
- /*
- * This Java ArrayList to Set example shows how to convert Java ArrayList to set
- * like HashSet.
- */
- public class JavaArrayListToSet {
- public static void main(String args[]){
- ArrayList<String> alistNumbers = new ArrayList<String>();
- alistNumbers.add("1");
- alistNumbers.add("2");
- alistNumbers.add("3");
- alistNumbers.add("1");
- /*
- * To convert Java ArrayList to Set, use
- * HashSet(Collection list)
- * constructor of HashSet class.
- */
- HashSet<String> hashSetNumbers = new HashSet<String>(alistNumbers);
- //print values of Set created from ArrayList
- System.out.println(hashSetNumbers);
- /*
- * Set implementation does not allow duplicate elements. As you can see
- * from the output after creating HashSet from ArrayList, duplicate
- * element 1 was also removed from the HashSet.
- */
- }
- }
- /*
- Output of above given Java ArrayList to Set would be
- [1, 2, 3]
- */

import java.util.List; import
More Arralist Examples
Post new comment