Nebneb 5
Nebneb 5

Reputation: 1

How do I convert an array of characters to a set?

How do I solve this error converting an array into a set?

String line = scan.nextLine();
char[] arr = line.toCharArray();
System.out.println(Arrays.toString(arr));
HashSet<Character> repeat = new HashSet<Character>(Arrays.asList(arr));
System.out.println(repeat);

The error is:

error: no suitable constructor found for HashSet(List<char[]>)

Upvotes: 0

Views: 1538

Answers (4)

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 79085

Java-9 solution:

Set<Character> repeat = line.chars()
                        .mapToObj(ch -> (char) ch)
                        .collect(Collectors.toSet());

Check String#chars and IntStream#mapToObj to learn more about them.

Upvotes: 0

user14838237
user14838237

Reputation:

You can use String.codePoints method for this porpose:

String line = "abcdeeadfc";

HashSet<Character> repeat = line.codePoints()
        .mapToObj(ch -> (char) ch)
        .collect(Collectors.toCollection(HashSet::new));

System.out.println(repeat); // [a, b, c, d, e, f]

See also: How do I add String to a char array?

Upvotes: 0

Neeraj Benjwal
Neeraj Benjwal

Reputation: 1351

@nebneb-5 Try this -

public class Test {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        String line = scan.nextLine();
        //char[] arr = line.toCharArray();
        List<Character> list = line.chars().mapToObj(c -> (char) c).collect(Collectors.toList());
        Set<Character> repeat = list.stream().collect(Collectors.toSet());
        System.out.println(repeat);
    }
}

Upvotes: 0

ernest_k
ernest_k

Reputation: 45319

Arrays.asList(arr) does not give you a List<Character> that you would use as Collection<Character> in your call to the HashSet constructor.

It gives List<char[]>, which would be an incorrect value as the expected Collection<Character> type. It's this conflict that's making your compilation fail.

The way to fix it is by creating a List<Character> and adding elements to it one by one, or, even simpler, to do that straight with the set itself:

Set<Character> repeat = new HashSet<>();
for(char c: arr)
    repeat.add(c);

There are many alternative approaches, but it boils down to copying elements from the char array to the set, via a list or not.

Upvotes: 2

Related Questions