Home » Java » How to convert an Array to a Set in Java

How to convert an Array to a Set in Java

Posted by: admin November 2, 2017 Leave a comment

Questions:

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);

Any ideas?

Answers:

Like this:

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

Questions:
Answers:
Set<T> mySet = new HashSet<T>();
Collections.addAll(mySet, myArray);

That’s Collections.addAll(java.util.Collection, T…) from JDK 6.

Additionally: what if our array is full of primitives?

For JDK < 8, I would just write the obvious for loop to do the wrap and add-to-set in one pass.

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

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

Questions:
Answers:

With Guava you can do:

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

Questions:
Answers:

Java 8:

String[] strArray = {"eins", "zwei", "drei", "vier"};

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

Questions:
Answers:

After you do Arrays.asList(array) you can execute Set set = new HashSet(list);

Here is a sample method, you can write:

public <T> Set<T> GetSetFromArray(T[] array) {
    return new HashSet<T>(Arrays.asList(array));
}

Questions:
Answers:

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

Set<String> set = Stream.of("A", "B", "C", "D").collect(Collectors.toCollection(HashSet::new));
System.out.println(set);

String[] stringArray = {"A", "B", "C", "D"};
Set<String> strSet1 = Arrays.stream(stringArray).collect(Collectors.toSet());
System.out.println(strSet1);

Set<String> 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]

Questions:
Answers:

Varargs will work too!

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

Questions:
Answers:

In Eclipse Collections, the following will work:

Set<Integer> set1 = Sets.mutable.of(1, 2, 3, 4, 5);
Set<Integer> set2 = Sets.mutable.of(new Integer[]{1, 2, 3, 4, 5});
MutableSet<Integer> mutableSet = Sets.mutable.of(1, 2, 3, 4, 5);
ImmutableSet<Integer> immutableSet = Sets.immutable.of(1, 2, 3, 4, 5);

Set<Integer> unmodifiableSet = Sets.mutable.of(1, 2, 3, 4, 5).asUnmodifiable();
Set<Integer> synchronizedSet = Sets.mutable.of(1, 2, 3, 4, 5).asSynchronized();
ImmutableSet<Integer> immutableSet = Sets.mutable.of(1, 2, 3, 4, 5).toImmutable();

Note: I am a committer for Eclipse Collections

Questions:
Answers:

Quickly : you can do :

// Fixed-size list
List list = Arrays.asList(array);

// Growable list
list = new LinkedList(Arrays.asList(array));

// Duplicate elements are discarded
Set set = new HashSet(Arrays.asList(array));

and to reverse

// Create an array containing the elements in a list
Object[] objectArray = list.toArray();
MyClass[] array = (MyClass[])list.toArray(new MyClass[list.size()]);

// Create an array containing the elements in a set
objectArray = set.toArray();
array = (MyClass[])set.toArray(new MyClass[set.size()]);

Questions:
Answers:

I’ve written the below from the advice above – steal it… it’s nice!

/**
 * Handy conversion to set
 */
public class SetUtil {
    /**
     * Convert some items to a set
     * @param items items
     * @param <T> works on any type
     * @return a hash set of the input items
     */
    public static <T> Set<T> asSet(T ... items) {
        return Stream.of(items).collect(Collectors.toSet());
    }
}

Questions:
Answers:

Sometime using some standard libraries helps a lot. Try to look at the Apache Commons Collections. In this case your problems is simply transformed to something like this

String[] keys = {"blah", "blahblah"}
Set<String> myEmptySet = new HashSet<String>();
CollectionUtils.addAll(pythonKeywordSet, keys);

And here is the CollectionsUtils javadoc

Questions:
Answers:
    private Map<Integer, Set<Integer>> nobreaks = new HashMap();
    nobreaks.put(1, new HashSet(Arrays.asList(new int[]{2, 4, 5})));
    System.out.println("expected size is 3: " +nobreaks.get(1).size());

the output is

    expected size is 3: 1

change it to

    nobreaks.put(1, new HashSet(Arrays.asList( 2, 4, 5 )));

the output is

    expected size is 3: 3

Questions:
Answers:

new HashSet<Object>(Arrays.asList(Object[] a));

But I think this would be more efficient:

final Set s = new HashSet<Object>();    
for (Object o : a) { s.add(o); }         

Questions:
Answers:
Set<String> set = org.mapstruct.ap.internal.util.Collections.asSet("one", "two");

Questions:
Answers:
Set<T> b = new HashSet<>(Arrays.asList(requiredArray));