How to convert Character array to Set

haosmark :

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.

Deadpool :

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=310075&siteId=1