Java中将字符串转换为HashSet

问题描述

我对将字符串转换为字符 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);
}

将输出:

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

试试这个:

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

输出:

{{1}}