Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert Character array to Set

Tags:

java

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.

like image 631
haosmark Avatar asked Oct 03 '19 02:10

haosmark


People also ask

Can we convert set to array?

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.

How do I turn a char array into a string?

The method valueOf() will convert the entire array into a string. String str = String. valueOf(arr);


1 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());
like image 69
Deadpool Avatar answered Sep 28 '22 06:09

Deadpool