【问题标题】:How do I convert an array of characters to a set?如何将字符数组转换为集合?
【发布时间】:2021-01-30 15:22:00
【问题描述】:

如何解决将数组转换为集合的错误?

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

错误是:

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

【问题讨论】:

    标签: java arrays collections char set


    【解决方案1】:

    Arrays.asList(arr) 不会为您提供 List&lt;Character&gt;,您可以在调用 HashSet 构造函数时将其用作 Collection&lt;Character&gt;

    它给出了List&lt;char[]&gt;,这将是一个不正确的值作为预期的Collection&lt;Character&gt; 类型。正是这种冲突导致您的编译失败。

    修复它的方法是创建一个List&lt;Character&gt; 并一个一个地向其中添加元素,或者更简单,直接使用集合本身来完成:

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

    有许多替代方法,但归结为通过列表或不通过列表将元素从 char 数组复制到集合。

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 收集到List&lt;Character&gt; 没有意义,只是再次流式传输并收集到Set&lt;Character&gt;。只需直接将第一个流收集到Set&lt;Character&gt;。此外,当您不使用该数组时,没有理由保留 char[] arr = line.toCharArray();
      • @Holger 我完全同意您的评论,但有时人们对那里的代码更具体。否则 ernest_k 提供的先前答案是完美的。
      • 这与具体无关。收集到List 在这里是一个完全过时的操作,所需时间几乎翻倍。
      【解决方案3】:

      你可以使用String.codePoints 方法来处理这个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]
      

      另见:How do I add String to a char array?

      【讨论】:

        【解决方案4】:

        Java-9 解决方案:

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

        查看String#charsIntStream#mapToObj 了解更多信息。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-11-30
          • 1970-01-01
          • 2013-12-02
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多