How to convert an Array to a Set in Java
Like this:
Set<T> mySet = new HashSet<>(Arrays.asList(someArray));
In Java 9+, if unmodifiable set is ok:
Set<T> mySet = Set.of(someArray);
In Java 10+, the generic type parameter can be inferred from the arrays component type:
var mySet = Set.of(someArray);
Be careful
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<Character> chars = Arrays.asList(new Character[] {'a', 'e', 'i', 'o', 'u', 'y'});
Set<Character> charSet = new HashSet<>(chars);
System.out.println(charSet);
or you can directly use Arrays.asList
Set<Character> charSet = new HashSet<>(Arrays.asList('a','e','i','o','u','y'));
Form jdk-9 there are Set.of
methods available to create immutable objects
Set<Character> chSet = Set.of('a','e','i','o','u','y');
You can also create unmodifiable Set by using Collections
Set<Character> set2 = Collections.unmodifiableSet(new HashSet<Character>(Arrays.asList(new Character[] {'a','e','i','o','u'})));
By using Arrays.stream
Character[] ch = new Character[] {'a', 'e', 'i', 'o', 'u', 'y'};
Set<Character> 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<Integer> set = new HashSet<>(Arrays.asList(arr));
or add the elements manually like
int[] arr = { 2, 6, 4, 2, 3, 3, 1, 7 };
Set<Integer> 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 <T> List<T> asList(T... a)
So if you do this:
List<Integer> list = Arrays.asList(1, 2, 3, 4)
or this:
List<Integer> 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<Integer> 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<Integer> 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<Foo> set = Arrays.stream(array)
.flatMap(Arrays::stream)
.collect(Collectors.toSet());
The above code snippet first creates a Stream<Foo[]>
with the Arrays.stream(array)
statement.
Then it flattens that stream into Stream<Foo>
with the second statement: .flatMap(Arrays::stream)
which behaves the same as .flatMap(arr -> Arrays.stream(arr))
.
At last it creates a Set<Foo>
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<Foo> 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();
}
Notes:
- Make certain that
n is <= max
, otherwise you could be waiting a while. max must be >= 1
(required byRandom.ints
method)
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 <= 0) {
throw new IllegalArgumentException(
"n(%d) <= max(%d) or max > 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.
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<int[]>
, such that the following is true:
Set<int[]> s = new HashSet<Integer>(ints);
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 = {5, 2, 7, 2, 4, 7, 8, 2, 3}; // java supports autoboxing when declaring an array
Set<Integer> s = new HashSet<Integer>(Arrays.asList(arr));
otherwise you will have to iterate and add the elements yourself.
int[] arr = {5, 2, 7, 2, 4, 7, 8, 2, 3};
Set<Integer> s = new HashSet<Integer>();
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));
Related Topics
Java 8: Performance of Streams VS Collections
Differencebetween Swing and Awt
What Could Cause Java.Lang.Reflect.Invocationtargetexception
Is It Unnecessary to Put Super() in Constructor
Interfaces with Static Fields in Java for Sharing 'Constants'
Why Does Hibernate Require No Argument Constructor
Deep Copy, Shallow Copy, Clone
Reusing a Preparedstatement Multiple Times
How to Call a Stored Procedure from Java and JPA
Redirect Console Output to String in Java
How to Convert an Int Array to String with Tostring Method in Java
Setmaxresults for Spring-Data-JPA Annotation
Is It Possible in Java to Access Private Fields via Reflection