Java – Conversion of Arrays to HashSet

In this article, we will discuss how to convert Arrays into Set

1. Conversion of Arrays into List using asList() method :

  • We can use inter-conversion constructor of HashSet
  • to convert Arrays into Set
  • by passing Arrays as constructor-argument

Method signature:

public static List asList(Object[] oArray);

Syntax:

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

ConvertArraysIntoSet.java

package in.bench.resources.java.collections;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class ConvertArraysIntoSet {

	public static void main(String[] args) {

		/*******************Integer Arrays example **************/

		// Integer Arrays
		Integer[] intArrays = {31, 83, 53, 97, 29, 7, 13,  47, 79};

		// conversion of Integer Arrays to Set (through List)
		SetSet<Integer> integerSet = new HashSetSet<Integer>(
				Arrays.asList(intArrays));

		// printing to console
		System.out.println("Conversion of"
				+ " Integer[] to Set<Integer>:\n\n"
				+ integerSet);

		/*******************String Arrays example **************/

		// String Arrays
		String[] strArrays = {
				"James",
				"Bond",
				"Mike",
				"Pups",
				"Bird"
		};

		// conversion of String Arrays to Set (through List)
		Set<String> strSet = new HashSet<String>(
				Arrays.asList(strArrays));

		// printing to console
		System.out.println("\n\n\nConversion of"
				+ " String[] to Set<String>:\n\n"
				+ strSet);
	}
}

Output:

Conversion of Integer[] to Set<Integer>:

[79, 31, 47, 13, 29, 7, 97, 53, 83]

Conversion of String[] to Set<String>:

[Pups, Bird, James, Bond, Mike]

Note:

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java - Sorting HashSet in Ascending and Descending order
Java - Conversion of HashSet to Arrays