简体   繁体   English

如何将字符数组转换为集合?

[英]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[]>)

Arrays.asList(arr) does not give you a List<Character> that you would use as Collection<Character> in your call to the HashSet constructor. Arrays.asList(arr)不会为您提供一个List<Character> ,您可以在调用HashSet构造函数时将其用作Collection<Character>

It gives List<char[]> , which would be an incorrect value as the expected Collection<Character> type.它给出了List<char[]> ,这将是一个不正确的值作为预期的Collection<Character>类型。 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:修复它的方法是创建一个List<Character>并一个一个地向它添加元素,或者更简单,直接用集合本身来做:

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.有许多替代方法,但归结为将元素从 char 数组复制到集合,无论是否通过列表。

@nebneb-5 Try this - @nebneb-5 试试这个 -

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

You can use String.codePoints method for this porpose:您可以为此 porpose 使用String.codePoints方法:

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?另请参阅:如何将字符串添加到字符数组?

Java-9 solution: Java-9 解决方案:

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

Check String#chars and IntStream#mapToObj to learn more about them.检查String#charsIntStream#mapToObj以了解有关它们的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM