0

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[]>)
Nebneb 5
  • 1
  • 3

4 Answers4

2

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.

ernest_k
  • 44,416
  • 5
  • 53
  • 99
0

@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);
    }
}
Neeraj Benjwal
  • 1,271
  • 10
  • 10
  • 1
    There is no point in collecting to a `List`, just to stream again and collect to a `Set`. Just collect the first stream to `Set` directly. Further, there’s no reason to keep the `char[] arr = line.toCharArray();` when you don’t use that array. – Holger Oct 16 '20 at 07:08
  • @Holger I am totally agree with your comment, but sometime people are more specific to there code. else the previous answer provided by ernest_k is perfect one. – Neeraj Benjwal Oct 16 '20 at 07:33
  • 1
    This has nothing to do with being specific. Collecting into a `List` is an entirely obsolete operation here that almost doubles the time needed. – Holger Oct 16 '20 at 07:36
0

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?

0

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.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110