

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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 Questions & Answers
- 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
- How to convert an array to Set and vice versa in Java?
- Program to convert set of Integer to Array of Integer in Java
- Program to convert Set to List in Java
- Write a program to convert an array to String in Java?
- How to convert an Array to a List in Java Program?
- Convert LinkedList to an array in Java
- Java Program to convert a List to a Set
- How to convert an object array to an integer array in Java?
Advertisements