如何解决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}}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。