简体   繁体   中英

Convert String to HashSet in Java

I am interested in converting a string to a HashSet of charcters, But HashSet takes in a collection in the constructor. I tried

HashSet<Character> result = new HashSet<Character>(Arrays.asList(word.toCharArray()));

(where word is the String) and it doesn't seem to work (maybe failed to box char into Character ?)

How should I do such conversion?

One quick solution using Java8 streams:

HashSet<Character> charsSet = str.chars()
            .mapToObj(e -> (char) e)
            .collect(Collectors.toCollection(HashSet::new));

Example:

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

Will output:

[r, s, t, e, g, i, n]

Try This:

      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]
  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM