
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Convert Array to Set and Vice Versa in Java
Array is a container which can hold a fix number of entities, which are of the same type. Each entity of an array is known as element and, the position of each element is indicated by an integer (starting from 0) value known as index.
Example
import java.util.Arrays; public class ArrayExample { public static void main(String args[]) { Number integerArray[] = new Integer[3]; integerArray[0] = 25; integerArray[1] = 32; integerArray[2] = 56; System.out.println(Arrays.toString(integerArray)); } }
Output
[25, 32, 56]
Whereas a Set object is a collection (object) stores another objects, it does not allow duplicate elements and allows at most null value.
Converting an array to Set object
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. Use this method to convert an array to Set.
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]
Set to array
The Set object provides a method known as toArray(). This method accepts an empty array as argument, converts the current Set to an array and places in the given array. Use this method to convert a Set object to an array.
Example
import java.util.HashSet; import java.util.Set; public class SetToArray { public static void main(String args[]){ Set<String> set = new HashSet<String>(); set.add("Apple"); set.add("Orange"); set.add("Banana"); System.out.println("Contents of Set ::"+set); String[] myArray = new String[set.size()]; set.toArray(myArray); for(int i=0; i<myArray.length; i++){ System.out.println("Element at the index "+(i+1)+" is ::"+myArray[i]); } } }
Output
Contents of Set ::[Apple, Orange, Banana] Element at the index 1 is ::Apple Element at the index 2 is ::Orange Element at the index 3 is ::Banana