Convert an ArrayList to HashSet in Java


To convert ArrayList to HashSet, firstly create an ArrayList −

List<String> l = new ArrayList<String>();

Add elements to the ArrayList −

l.add("Accent");
l.add("Speech");
l.add("Diction");
l.add("Tone");
l.add("Pronunciation");

Now convert the ArrayList to HashSet −

Set<String> s = new HashSet<String>(l);

The following is an example to convert an ArrayList to HashSet in Java.

Example

 Live Demo

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.HashSet;
public class Main {
   public static void main(String[] args) {
      List<String> l = new ArrayList<String>();
      l.add("Accent");
      l.add("Speech");
      l.add("Diction");
      l.add("Tone");
      l.add("Pronunciation");
      Set<String> s = new HashSet<String>(l);
      System.out.println("HashSet elements...");
      for (Object ob : s)
      System.out.println(ob);
   }
}

Output

HashSet elements...
Tone
Pronunciation
Accent
Speech
Diction

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 30-Jul-2019

791 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements