- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java program to convert an Array to Set
The Arrays class of the java.util package provides a method known as asList(). This method accepts an array as an argument and, returns a List object. To convert an array to a Set object −
- Create an array or read it from the user.
- Using the asList() method of the Arrays class convert the array to a list object.
- Pass this list to the constructor of the HashSet object.
- Print the contents of the Set object.
Example
import java.util.Arrays; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class ArrayToSet { public static void main(String args[]){ Scanner sc = new Scanner(System.in); System.out.println("Enter the size of the array to be created ::"); int size = sc.nextInt(); String [] myArray = new String[size]; for(int i=0; i<myArray.length; i++){ System.out.println("Enter the element "+(i+1)+" (String) :: "); myArray[i]=sc.next(); } Set<String> set = new HashSet<>(Arrays.asList(myArray)); System.out.println("Given array is converted to a Set"); System.out.println("Contents of set ::"+set); } }
Output
Enter the size of the array to be created :: 4 Enter the element 1 (String) :: Ram Enter the element 2 (String) :: Rahim Enter the element 3 (String) :: Robert Enter the element 4 (String) :: Rajeev Given array is converted to a Set Contents of set ::[Robert, Rahim, Rajeev, Ram]
- Related Articles
- Java program to convert a Set to an array
- Java Program to convert a set into an Array
- Program to convert Array to Set in Java
- How to convert an Array to a Set in Java?
- Java program to convert a list to an array
- Java program to convert an array to a list
- Program to convert Stream to an Array in Java
- Swift Program to Convert Array to Set
- Golang Program To Convert Array To Set
- Program to convert set of Integer to Array of Integer in Java
- How to convert an array to Set and vice versa in Java?
- C++ Program to Convert Array to Set (Hashset)
- Haskell Program to Convert Array to Set (HashSet)
- Swift Program to Convert Set into Array
- Write a program to convert an array to String in Java?

Advertisements