我对将字符串转换为charcters的HashSet
很感兴趣,但是HashSet
在构造函数中接受一个集合。我试过了
HashSet<Character> result = new HashSet<Character>(Arrays.asList(word.toCharArray()));
( word
是字符串),但它似乎不起作用(可能无法将char
装箱到Character
中?)
我应该如何进行这种转换呢?
发布于 2021-04-16 11:41:38
一种使用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]
发布于 2021-04-16 18:22:45
试试这个:
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]
https://stackoverflow.com/questions/67124435
复制相似问题