[英]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.