簡體   English   中英

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);
}

請問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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM