How to count the unique words in a string with Java

1 Answer

0 votes
import java.util.Arrays;
import java.util.HashSet;
 
public class MyClass {
    public static void main(String args[]) {
        String s = "python javascript c c++ php c++ php java javascript python";
          
        String[] words = s.split(" ");
          
        HashSet<String> unique_words = new HashSet<String>(Arrays.asList(words));
          
        System.out.println(unique_words.size());
    }
}
 
 
 
 
/*
run:
 
6
 
*/

 



answered May 3, 2022 by avibootz

Related questions

1 answer 185 views
1 answer 144 views
1 answer 98 views
1 answer 102 views
1 answer 134 views
1 answer 115 views
1 answer 114 views
...