On this java tutorial, we will be learning on how to convert an Array to Set. A Set is a part of Java Collections framework that doesn’t allow duplicates on it’s elements. Meaning to say that all constructors should create a set that contains no duplicate elements.
Array to Set Conversion source code
This java source code shows how to convert an Array of strings to a Set. The behavior of a Set is it doesn’t allow duplicates as we have already mentioned, thus any further attempt to add an element to the set will just ignore it if the value of the element is already on the collections. We have added a check on the size of the set before and after we have added an element. The conversion is done by passing a list to HashSet constructor. As we have already provided an example on converting java Array to List, we will be leveraging this method to pass a List to our constructor.
package com.javatutorialhq.tutorial; import java.util.Arrays; import java.util.HashSet; import java.util.Set; /* * Java tutorial Example source code to convert an Array to Set of Strings */ public class ArrayToSet { public static void main(String[] args) { // instantiating an array of Strings String[] arrayString = new String[]{"grace","michael","anne"}; // convert the Array to Set Set set = new HashSet<>(Arrays.asList(arrayString)); for(String s:set){ System.out.println(s); } // getting first the size of the set System.out.println("Initial size of set:"+set.size()); // add a duplicate string to our set set.add("grace"); System.out.println("Size of the set after adding:"+set.size()); } }
Sample Output in the running the java program to convert an array to set
grace michael anne Initial size of set:3 Size of the set after adding:3
You can also refer to our article Set to Array conversion examples, if you are interested on the the reverse conversion.