How to add all elements of ArrayList to HashSet in Java

1 Answer

0 votes
package javaapplication1;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;

public class JavaApplication1 {

    public static void main(String[] args) {

        try {

            ArrayList<String> list = new ArrayList<>();
            list.add("java");
            list.add("c");
            list.add("c++");
            list.add("c#");

            HashSet<String> hash = new HashSet<>();
            hash.addAll(list);

            Iterator itr = hash.iterator();

            while (itr.hasNext()) {
                System.out.println(itr.next());
            }

        } catch (Exception e) {
            System.out.print(e.toString());
        }
    }
}

/*
             
run:

c#
c++
java
c
    
 */

 



answered Nov 30, 2016 by avibootz

Related questions

1 answer 211 views
1 answer 217 views
2 answers 269 views
1 answer 192 views
1 answer 199 views
199 views asked Apr 27, 2020 by avibootz
1 answer 119 views
119 views asked Jul 23, 2023 by avibootz
...