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