在 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);
}
将输出:
[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);
输出:
[p, d, u, h, l, o]
我有兴趣将字符串转换为 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]
试试这个:
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]