How to convert Character array to Set

Viewed 11248

How do I add a list of chars into a set? The code below doesn't seem to work.

HashSet<Character> vowels = new HashSet<Character>(
        new Character[] {'a', 'e', 'i', 'o', 'u', 'y'}
    );

The error that I'm seeing is

The constructor HashSet(Character[]) is undefined

I tried both, Character[] and char[], but neither is working.

3 Answers

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());
Set<Character> vowels = new HashSet<Character>(Arrays.asList(new Character[] {'a', 'e', 'i', 'o', 'u', 'y'}));

Since Set is a part of the Collection package in Java. Therefore the Array can be converted into the Set with the help of Collections.addAll() method.

 // Crate an Empty Set
 Set<T> set = new HashSet<>(); 
  
  // Add the Character array to set 
  Collections.addAll(set, Arrays.toCharacter( new Character[] {'a', 'e', 'i', 'o', 'u', 'y'}));
Related