【问题标题】:Convert String to HashSet in Java在 Java 中将 String 转换为 HashSet
【发布时间】:2021-07-11 10:23:46
【问题描述】:

我有兴趣将字符串转换为 HashSet 的字符,但 HashSet 在构造函数中接受一个集合。我试过了

HashSet<Character> result = new HashSet<Character>(Arrays.asList(word.toCharArray()));

(其中word 是字符串)并且它似乎不起作用(可能无法将char 放入Character 中?)

我应该如何进行这种转换?

【问题讨论】:

  • 回复:“可能无法将char 装箱到Character”:这不是将char 自动装箱到Character 的问题,而是将char[] 自动装箱到Character[] 的问题-- 不支持。 (将char 自动装箱到Character 不仅仅是编译时转换,它还涉及在运行时实际创建或检索Character 实例。因此将char[] 自动装箱到Character[] 将涉及自动循环数组等)

标签: java string char type-conversion hashset


【解决方案1】:

试试这个:

      String word="holdup";
      char[] ch = word.toCharArray();
      HashSet<Character> result = new HashSet<Character>();
      
      for(int i=0;i<word.length();i++)
      {
        result.add(ch[i]);
      }
       System.out.println(result);


     

输出:

 [p, d, u, h, l, o]
  

【讨论】:

    【解决方案2】:

    使用 Java8 流的一种快速解决方案:

    HashSet<Character> charsSet = str.chars()
                .mapToObj(e -> (char) e)
                .collect(Collectors.toCollection(HashSet::new));
    

    例子:

    public static void main(String[] args) {
        String str = "teststring";
        HashSet<Character> charsSet = str.chars()
                .mapToObj(e -> (char) e)
                .collect(Collectors.toCollection(HashSet::new));
        System.out.println(charsSet);
    }
    

    将输出:

    [r, s, t, e, g, i, n]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-25
      • 1970-01-01
      • 2021-07-14
      • 1970-01-01
      • 2021-07-25
      • 2011-02-02
      相关资源
      最近更新 更多