Convert an ArrayList to HashSet in Java

Java 8Object Oriented ProgrammingProgramming

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
raja
Published on 30-Jan-2019 10:18:07
Advertisements