Program to convert Array to Set in Java

Java 8Object Oriented ProgrammingProgramming

Let’s say the following is our array of strings −

String arr[] = { "Andy", "John", "Kevin", "Mary", "Ryan" };

Now, convert the array to set with HashSet −

Set<String>set = new HashSet<>(Arrays.asList(arr));

Example

Following is the program to convert Array to Set in Java −

import java.util.*;
public class Demo {
   public static void main(String[] args) {
      String arr[] = { "Andy", "John", "Kevin", "Mary", "Ryan" };
      System.out.println("Array = "+ Arrays.toString(arr));
      Set<String>set = new HashSet<>(Arrays.asList(arr));
      System.out.println("Set = " + set);
   }
}

Output

Array = [Andy, John, Kevin, Mary, Ryan]
Set = [Kevin, Ryan, John, Andy, Mary]
raja
Published on 25-Sep-2019 07:47:19
Advertisements