Java stream array to set

Convert array to Set (HashSet) Example

Convert array to Set Example shows how to convert array to Set (HashSet) in Java using various approaches including addAll method, constructor, Java 8 stream, and apache commons.

How to convert array to Set (HashSet)?

There are several ways using which you can convert array to Set (HashSet) as given below.

1) Using the HashSet constructor

You can first convert an array to List using the asList method of the Arrays class and then use the constructor of the HashSet class which accepts another collection parameter as given below.

2) Using the addAll method of HashSet

You can first convert an array to List using the asList method of the Arrays class and then add all the elements of the List to HashSet using the addAll method of the HashSet as given below.

3) Using the addAll method of Collections

Alternatively, you can use the addAll method of the Collections class as well to add all the elements of an array to the HashSet as given below.

4) Using for loop

Loop through an array and add all the elements of an array to the HashSet one by one as given below.

5) Using Apache Commons

If you are using the Apache Commons library, you can use the addAll method of the CollectionUtils class to add all the elements of an array to HashSet as given below.

6) Using stream (Java 8)

If you are using Java 8, you can use a stream as given below.

7) Using the toCollection method of Collectors (Java 8)

If you are using Java 8, you can use the toCollection method and stream as given below.

We had 5 elements in the array but when we converted an array to HashSet, only 4 elements were added. What happened to the missing one element? If you look carefully, array contained the “Java” element twice. The HashSet class does not allow duplicate elements and thus it was removed when the array was converted to the HashSet.

Please let me know your views in the comments section below.

About the author

I have a master’s degree in computer science and over 18 years of experience designing and developing Java applications. I have worked with many fortune 500 companies as an eCommerce Architect. Follow me on LinkedIn and Facebook.

Читайте также:  Тип datetime python pandas

Источник

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.

Источник

Convert Array to TreeSet in Java Example

This example shows how to convert an array to TreeSet in Java. This example also shows how to convert array to TreeSet using constructor, addAll method, Collections class, for loop, and Java 8 stream.

How to convert an Array to TreeSet in Java?

There are several ways using which we can convert an array to TreeSet object as given below. I am going to use an Integer array for the purpose of this example.

1. Using for loop

The simplest way is to loop through an array and add elements to the TreeSet object one by one as given below.

2. Using TreeSet constructor

We can use the TreeSet constructor that accepts a collection object, but for that, we need to convert an array to a collection first. We can use the asList method of the Arrays class that returns a List wrapper around an array to do that.

3. Using the TreeSet addAll method

The addAll method of the TreeSet class adds all elements of the specified collection object to the set object. We are going to convert array to a List using the same asList method of the Arrays class and then use the addAll method.

4. Using Collections addAll method

Instead of the addAll method of the TreeSet class, we can also use the addAll method of the Collections class as given below.

5. Using Apache Commons CollectionUtils class

If you are using the Apache Commons library, we can use the addAll method of the CollectionUtils class to convert an array to a TreeSet object.

6. Using Java 8 Stream

If you are using Java version 8 or later, you can use the Java stream to convert an array to a set as given below.

As we can see from the output, the TreeSet class automatically sorts the array elements in their natural order i.e. ascending order for the type Integer. Also, the original array contained 6 elements, but when we converted it to an array, we got only 5 elements.

Читайте также:  Си шарп массивы в классе

It is because the TreeSet is an implementation of the Set interface that does not allow duplicate elements hence the last element “2” was not added to the TreeSet as it was duplicated.

Please also visit how to convert TreeSet to an array example to know more.

Please let me know your views in the comments section below.

About the author

I have a master’s degree in computer science and over 18 years of experience designing and developing Java applications. I have worked with many fortune 500 companies as an eCommerce Architect. Follow me on LinkedIn and Facebook.

Источник

How to Convert an Array to a Set in Java

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

var mySet = Set.of(someArray);

Set.of throws IllegalArgumentException — if there are any duplicate
elements in someArray.
See more details: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Set.html#of(E. )

How to convert Character array to Set

First convert the Character array into List and then use HashSet<>() constructor to convert into Set

List chars = Arrays.asList(new Character[] );
Set charSet = new HashSet<>(chars);
System.out.println(charSet);

or you can directly use Arrays.asList

Set charSet = new HashSet<>(Arrays.asList('a','e','i','o','u','y'));

Form jdk-9 there are Set.of methods available to create immutable objects

You can also create unmodifiable Set by using Collections

Set set2 = Collections.unmodifiableSet(new HashSet(Arrays.asList(new Character[] )));
Character[] ch = new Character[] ;
Set set = Arrays.stream(ch).collect(Collectors.toSet());

How to add an Array into Set properly?

You need to use the wrapper type to use Arrays.asList(T. )

Integer[] arr = < 2, 6, 4, 2, 3, 3, 1, 7 >;
Set set = new HashSet<>(Arrays.asList(arr));

or add the elements manually like

int[] arr = < 2, 6, 4, 2, 3, 3, 1, 7 >;
Set set = new HashSet<>();
for (int v : arr) set.add(v);
>

Finally, if you need to preserve insertion order, you can use a LinkedHashSet .

Java int[] array to HashSet Integer

Some further explanation. The asList method has this signature

public static List asList(T. a)
List list = Arrays.asList(1, 2, 3, 4)
List list = Arrays.asList(new Integer[] < 1, 2, 3, 4 >)

In these cases, I believe java is able to infer that you want a List back, so it fills in the type parameter, which means it expects Integer parameters to the method call. Since it’s able to autobox the values from int to Integer, it’s fine.

However, this will not work

List list = Arrays.asList(new int[] < 1, 2, 3, 4>)

because primitive to wrapper coercion (ie. int[] to Integer[]) is not built into the language (not sure why they didn’t do this, but they didn’t).

As a result, each primitive type would have to be handled as it’s own overloaded method, which is what the commons package does. ie.

public static List asList(int i. );

How to convert 2 dimensional array to Set?

A simple (but not the best performing) solution would be to use java streams:

Set set = Arrays.stream(array) 
.flatMap(Arrays::stream)
.collect(Collectors.toSet());

The above code snippet first creates a Stream with the Arrays.stream(array) statement.

Then it flattens that stream into Stream with the second statement: .flatMap(Arrays::stream) which behaves the same as .flatMap(arr -> Arrays.stream(arr)) .

At last it creates a Set out of the flattened stream with .collect(Collectors.toSet()) .

I suggest having a deep look at the Java Streaming API, introduced with Java 8. It can do much more than just mapping a 2d array into a Set.

Another approach is just to use 2 nested for loops:

Set set = new HashSet<>(); // or LinkedHashSet if you need a similar order than the array
for(Foo[] inner : array) for(Foo item : inner) set.add(item);
>
>

How can I convert my Set to an array efficiently?

Don’t use a set. Stream the random numbers, remove dups using distinct , and limit using limit

public static int [] randArr(int n, int max) Random rn = new Random(); 
return rn.ints(0,max).distinct().limit(n).toArray();
>

You may want to put in some code to enforce those invariants and throw an appropriate exception if not in compliance. Something like the following (or whatever makes sense to you).

if (n > max || max throw new IllegalArgumentException( 
"n(%d) 0 not in compliance"
.formatted(n,max));
>

Compile error while converting array to Set in java

Your problem is the call to Arrays.asList(arr) . It has gotten confused by the use of a primitive array. Java treats primitives and objects differently.

Читайте также:  Random Numbers Generator

asList only knows about arrays of objects, and in your case it is treating the entire array as a single element. That is, asList(arr) is returning Set , such that the following is true:

Which is not what you meant.

There is no auto boxing of primitive arrays in Java. The quickest fix is to use Integer rather than int for the input array:

Integer[] arr = ; // java supports autoboxing when declaring an array 
Set s = new HashSet(Arrays.asList(arr));

otherwise you will have to iterate and add the elements yourself.

int[] arr = ;
Set s = new HashSet();
for ( int v : arr ) s.add(v); // autoboxing of a single int is supported by Java, and happens here
>

Add values from basic array to Set String

I think you can convert your array to a list first. Maybe something like

this.fields.addAll(Arrays.asList(s));

Источник

How to Convert Array to Set in Java

In this post, we are going to convert an array to set by using Java co de. An Array is an index based data structure that is used to store similar types of data while the set is a collection of unique elements.

Here, we have several examples to convert an array to set, always remember that set contains unique elements only so duplicate elements of the array will not add to the set during conversion.

Here, we used addAll() , asList() and toSet() methods to get set from array elements. The addAll() method is a Collections class method that adds array elements to the specified collection(list, set, etc)

Time for an Example

Let’s take an example to convert an array to Set. Here, we used addAll() method to add elements into the set. This is pretty easy to get set from an array.

import java.util.Collections; import java.util.HashSet; import java.util.Set; public class Main < public static void main(String[] args)< String[] fruits = ; for (int i = 0; i < fruits.length; i++) < System.out.println(fruits[i]); >Set fruitsSet = new HashSet<>(); Collections.addAll(fruitsSet, fruits); System.out.println(fruitsSet); > >

Apple
Orange
Banana
Orange
[Apple, Orange, Banana]

Example:

We can use asList() method to get convert array to set. The asList() method returns a list of the array that further is converted by the constructor to a set. See the below example.

import java.util.Arrays; import java.util.HashSet; import java.util.Set; public class Main < public static void main(String[] args)< String[] fruits = ; for (int i = 0; i < fruits.length; i++) < System.out.println(fruits[i]); >Set fruitsSet = new HashSet<>(Arrays.asList(fruits)); System.out.println(fruitsSet); > >

Apple
Orange
Banana
Orange
[Apple, Orange, Banana]

Example: Java 8

Let’s create another example to get set from array elements. Here, we are using the toSet() method of Collectors class that returns set from the stream elements. This example is useful if you want to use the stream to get set elements.

import java.util.Arrays; import java.util.HashSet; import java.util.Set; import java.util.stream.Collectors; public class Main < public static void main(String[] args)< String[] fruits = ; for (int i = 0; i < fruits.length; i++) < System.out.println(fruits[i]); >Set fruitsSet = new HashSet<>(); fruitsSet = Arrays.stream(fruits).collect(Collectors.toSet()); System.out.println(fruitsSet); > >

Apple
Orange
Banana
Orange
[Apple, Orange, Banana]

Источник

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