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.
Create a Set object. Add elements to it. Create an empty array with size of the created Set. Convert the Set to an array using the toArray() method, bypassing the above-created array as an argument to it.
The method valueOf() will convert the entire array into a string. String str = String. valueOf(arr);
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With