How to convert an Array to a Set in Java?

In This tutorial, we will Learn How to convert an Array to a Set in Java? We can do say this using two ways one is a native method where we simply iterate the array and keep storing the elements in a pre-initialized set. And another method could be using the inbuild function set.of() and passing the array in arguments.

Convert The Array In To Set

Ways To Convert The Array In To Set

There are two ways to convert an array in to set here we will discuss both of them one by one And followed by some examples explaining and some live examples.

Native Method

It is the method when we simply iterate the whole array and keep on storing the elements in a set one by one To Understand in a better way just follow the example given below and try to learn.

public class ArrayToListExample1 {
 public static void main(String args[]) {
 String array[] = { "Golf", "Soccer", "Baseball", "Volleyball", "Tennis", "Badminton", "Rugby", "Archery", "Skiing"};
 Set<T> mySet = new HashSet<>();
 for (T t : array) {
 list.add(t);
 } 
return list;
 } }

Here we simply string the elements of an array in a set one after another.

Using set.of()  Method

As we know there is another way to do the same thing using an inbuilt method in simple and in a single line so let’s explore it also and understand using an example of how it makes it so simple and gets it done.

public class ArrayToListExample1 {
 public static void main(String args[]) {
 String array[] = { "Golf", "Soccer", "Baseball", "Volleyball", "Tennis", "Badminton", "Rugby", "Archery", "Skiing"};
Set<T> mySet = new HashSet<>(Arrays.asList(someArray));
System.out.println( myset );

Here we can directly convert the array into a set and print or we also perform some important operations.

 

Learn More about How to convert an Array to a Set in Java? At Array To Set Conversion

Also, Visit Java Tutorials And learn and get resolved your problems also visit Python’s list: What is the difference Between methods Append and Extend?  for learning about Python and keep learning about different programming languages.

Leave a Comment

%d bloggers like this: