繁体   English   中英

Java中的String转换为HashSet

[英]Convert String to HashSet in Java

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

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

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

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

一种使用 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);
}

请问output:

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

尝试这个:

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


     

Output:

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

暂无
暂无

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

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