有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在Java中将字符串转换为哈希集

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

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

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

我应该如何进行这种转换


共 (2) 个答案

  1. # 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. # 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]