Java set from array

How to convert an Array to a Set in Java

I would like to convert an array to a Set in Java. There are some obvious ways of doing this (i.e. with a loop) but I would like something a bit neater, something like:

java.util.Arrays.asList(Object[] a); 

19 Answers 19

Set mySet = new HashSet<>(Arrays.asList(someArray)); 

In Java 9+, if unmodifiable set is ok:

Set mySet = Set.of(someArray); 

In Java 10+, the generic type parameter can be inferred from the arrays component type:

var mySet = Set.of(someArray); 

Note that if you use this method on an array of primitives such as int[] it will return a List so you should use wrapper classes to get the intended behavior.

Set mySet = new HashSet(); Collections.addAll(mySet, myArray); 

Additionally: what if our array is full of primitives?

For JDK >= 8, an attractive option is something like:

Arrays.stream(intArray).boxed().collect(Collectors.toSet()); 

You can do that with java.util.Collections.addAll . Plus, I wouldn’t recommend Commons Collections anymore, what with it not being generified and Guava existing .

I believe Adrian’s point was about how SLaks’ solution creates a List instance which is ultimately thrown out. The actual impact of that difference is probably extremely minimal, but could depend on the context in which you’re doing this — tight loops or very large sets might behave very differently between these two options.

Per the Collections.addAll() javadoc (Java 6): «The behavior of this convenience method is identical to that of c.addAll(Arrays.asList(elements)), but this method is likely to run significantly faster under most implementations.»

T[] array = . Set set = Sets.newHashSet(array); 

For a fixed list of elements you could use: ImmutableSet.of(e1, e2, . en). Notice you would not be able to change this Set after its creation.

Be warned, the Guava javadoc says: «This method is not actually very useful and will likely be deprecated in the future.» They point towards the standard new HashSet(Arrays.asList(someArray)) . See google.github.io/guava/releases/19.0/api/docs/com/google/common/…

String[] strArray = ; Set strSet = Arrays.stream(strArray).collect(Collectors.toSet()); System.out.println(strSet); // [eins, vier, zwei, drei] 

@RaffiKhatchadourian This is not necessarily being done in parallel. Arrays.stream does not make any promises on the stream. You would have to call parallel() on the resulting stream for that.

You could also call parallelStream(). To answer @RaffiKhatchadourian’s question, probably not. Try measuring if you’re noticing any performance issues.

Читайте также:  Python import csv data

Generally, avoid parallel. By default it uses a single threadpool accross your application, and the overhead to start threads and join is worse than sequentially streaming through hundreds of items. Only in very few situations does parallel actually bring benefit.

Stream.of(T. values).collect(Collectors.toSet()); 

Java 8

We have the option of using Stream as well. We can get stream in various ways:

Set set = Stream.of("A", "B", "C", "D").collect(Collectors.toCollection(HashSet::new)); System.out.println(set); String[] stringArray = ; Set strSet1 = Arrays.stream(stringArray).collect(Collectors.toSet()); System.out.println(strSet1); // if you need HashSet then use below option. Set strSet2 = Arrays.stream(stringArray).collect(Collectors.toCollection(HashSet::new)); System.out.println(strSet2); 

The source code of Collectors.toSet() shows that elements are added one by one to a HashSet but specification does not guarantee it will be a HashSet .

«There are no guarantees on the type, mutability, serializability, or thread-safety of the Set returned.»

So it is better to use the later option. The output is: [A, B, C, D] [A, B, C, D] [A, B, C, D]

Immutable Set (Java 9)

Java 9 introduced Set.of static factory method which returns immutable set for the provided elements or the array.

@SafeVarargs static Set of​(E. elements) 

Immutable Set (Java 10)

We can also get an immutable set in two ways:

The method Collectors.toUnmodifiableList() internally makes use of Set.of introduced in Java 9. Also check this answer of mine for more.

Источник

Java Array to Set

In this tutorial we will learn about How to convert java array to Set . We will discuss how to convert array to Set in java using constructor , set.addAll() method , Collections.addAll() method and loop over array .Please Don’t use duplicate elements in the array, because duplicates will be discarded in the set.

Convert array to Set In Java

Now we will see different approaches for how to convert array to Set in java.

1. Java Array to Set using TreeSet Constructor

In this example we will create a array of Strings. Now we will initialize TreeSet Using Parameterized Constructor with the array (arr) elements .

import java.util.Arrays; import java.util.Set; import java.util.TreeSet; public class ArrayToSet < public static void main(String[] args) < //create array of Strings String [] arr=; for (String element : arr) < System.out.println("Array element is : "+element); >//initialize Set using array elements Set set = new TreeSet(Arrays.asList(arr)); // print TreeSet Element System.out.println("Set Elements : "+ set); > >
Array element is : java Array element is : vogue Array element is : welcomes Set Elements : [java, vogue, welcomes]

2. Convert Array to Set using Set.addAll() method

In this example we will convert array to Set in java using addAll() method of Set . Firstly we created array (arr) of Strings .Now we will create Set , then add array elements to it using Set.addAll() method . Let,s see java program add array element to set in java.

import java.util.Arrays; import java.util.Set; import java.util.TreeSet; public class ArrayToSet1 < public static void main(String[] args) < // create array of Strings String[] arr = < "java", "vogue", "welcomes" >; for (String element : arr) < System.out.println("Array element is : " + element); >Set set = new TreeSet(); //adding arr elements to the Set using the addAll() method set.addAll(Arrays.asList(arr)); // print TreeSet Element System.out.println("Set Elements : " + set); > >
Array element is : java Array element is : vogue Array element is : welcomes Set Elements : [java, vogue, welcomes]

3. Java Array to Set using Collections.addAll() method

We can convert array to Set in java using Collections.addAll() method. We created array (arr) of Strings firstly .Now We will create Set , then add array elements to it using Collections.addAll() method .

import java.util.Collections; import java.util.Set; import java.util.TreeSet; public class ArrayToSet2 < public static void main(String[] args) < // create array of Strings String[] arr = < "java", "vogue", "welcomes" >; for (String element : arr) < System.out.println("Array element is : " + element); >Set set = new TreeSet(); //adding elements of array to Set using Collections.addAll() method Collections.addAll(set, arr); // print TreeSet Element System.out.println("Set Elements : " + set); > >
Array element is : java Array element is : vogue Array element is : welcomes Set Elements : [java, vogue, welcomes]

4. Convert Array to Set Using add() Method

In this approach,we will convert array (arr) to Set in java using for loop . We create array of Strings and add some elements into it. We also created one Set. Now We Iterate array (arr) element Using for-each loop and one by one element of array(arr) will added to Set using add() method . Let,s see java program for this approach.

import java.util.Set; import java.util.TreeSet; public class ArrayToSet3 < public static void main(String[] args) < // create array of Strings String[] arr = < "java", "vogue", "welcomes" >; for (String element : arr) < System.out.println("Array element is : " + element); >Set set = new TreeSet(); for (String element : arr) < //add element from array to Set set.add(element); >// print TreeSet Element System.out.println("Set Elements : " + set); > >
Array element is : java Array element is : vogue Array element is : welcomes Set Elements : [java, vogue, welcomes]

In this tutorial we have learned java array to set conversion using different approaches . You can see more java TreeSet Program for practice .

Читайте также:  Rpm python is needed

Источник

Java Program to Convert Array to Set (HashSet) and Vice-Versa

To understand this example, you should have the knowledge of the following Java programming topics:

Example 1: Convert Array to Set

import java.util.*; public class ArraySet < public static void main(String[] args) < String[] array = ; Set set = new HashSet<>(Arrays.asList(array)); System.out.println("Set: " + set); > >

In the above program, we have an array named array . To convert array to set , we first convert it to a list using asList() as HashSet accepts a list as a constructor.

Then, we initialize the set with the elements of the converted list.

Example 2: Convert Array to Set using stream

import java.util.*; public class ArraySet < public static void main(String[] args) < String[] array = ; Set set = new HashSet<>(Arrays.stream(array).collect(Collectors.toSet())); System.out.println("Set: " + set); > >

The output of the program is the same as Example 1.

In the above program, instead of converting an array to list and then to a set, we use a stream to convert to set.

We first convert the array to stream using stream() method and use collect() method with toSet() as a parameter to convert the stream to a set.

Example 3: Convert Set to Array

import java.util.*; public class SetArray < public static void main(String[] args) < Setset = new HashSet<>(); set.add("a"); set.add("b"); set.add("c"); String[] array = new String[set.size()]; set.toArray(array); System.out.println("Array: " + Arrays.toString(array)); > >

In the above program, we have a HashSet named set . To convert set into an array , we first create an array of length equal to the size of the set and use toArray() method.

Источник

Examples of Conversion Between Array and Set in Java

This tutorial illustrates examples to Convert an Array to a Set, as well as Convert a Set to an Array using Plain Java, Guava, and Apache Commons Collections API.

Читайте также:  Язык php программа обучения

Set to Array Convertion

First, we will see examples of converting a Java Set to an Array.

Using Plain Java

We can use the toArray method on the Set to convert it to an Array.

Set integerSet = Set.of(10, 20, 30); Integer[] integerArray = integerSet.toArray(new Integer[0]); Code language: Java (java)

Although, by default the method returns an array of Object class, we can pass an empty Integer array to get the results in the form of array of Integers.

Using Guava Library

Alternatively, we can use Guava API to achieve the conversion.

Set integerSet = Set.of(10, 20, 30); int[] integerArray = Ints.toArray(integerSet);Code language: Java (java)

Array to Set Conversion

Now that we have seen a couple of ways to convert a Set to an Array, not we will do the other way.

Most importantly, Set is a collection of unique elements. Thus, when we convert an array with duplicate elements to Set, we find the duplicate elements are removed.

Using Plain Java

There are a few ways to convert an Array into Set. The most basic way is to use the factory methods of Set interface. However, the factory methods produce an Immutable Set instance.

Integer[] integerArray = new Integer[]12, 20, 30>; Set integerSet = Set.of(integerArray);Code language: Java (java)

Alternatively, we can first convert Array to a List and use the list to create a HashSet . Remember, the Set we create using constructor is a mutable Set.

Integer[] integerArray = new Integer[]12, 20, 30>; Set integerSet = new HashSet<>(Arrays.asList(integerArray));Code language: Java (java)

Finally, we can also create an empty set first and then populate it with array elements by using Collections .

Integer[] integerArray = new Integer[]12, 20, 30>; Set integerSet = new HashSet<>(); Collections.addAll(integerSet, integerArray);Code language: Java (java)

Using Guava Library

The Guava Library provides Set which is a utility class. We can use Sets#newHashSet method to create a Set from an array.

Integer[] integerArray = new Integer[]12, 20, 30>; Set integerSet = Sets.newHashSet(integerArray);Code language: Java (java)

Using Apache Commons Collections Library

Lastly, we will use Apache Commons Collections Library to convert an array to a Set.

Integer[] integerArray = new Integer[]12, 20, 30>; Set integerSet = new HashSet<>(); CollectionUtils.addAll(integerSet, integerArray);Code language: Java (java)

Summary

In this short tutorial we studied various way of Converting an Array to a Set and Converting a Set to an Array. We covered examples using Plain Java, Guava Library, and Apache Commons Library. For more Java Tutorials, please visit Java Tutorials.

Источник

Оцените статью