Occurrence of a word in a sentence I have written Java code that finds the frequency of the occurrence of a word in a sentence.  It is working fine.  The only thing I want to do is to optimize this code.

String str = "I am a Boy I am a";
        String[] splitStr = str.split(" ");
        int count = 0;
        List&lt;String&gt; list = new ArrayList&lt;&gt;();
        for(String s:splitStr){
            if(!list.contains(s)){
                list.add(s);
            }
        }
        for(int i=0;i&lt;list.size();i++){
            for(int j=0;j&lt;splitStr.length;j++){
                if(list.get(i).equals(splitStr[j])){
                    count++;
                }
            }
            System.out.println("Occurrence of " + list.get(i) + " is " + count + " times.");
            count=0;
        }
You can simplify your code to a great extent by using a Map&lt;String, Integer&gt; instead of List&lt;String&gt;. The map would store the mapping from each word to it's count in the array. 

You can modify your code like so:

String str = "I am a Boy I am a";
String[] splitStr = str.split(" ");

Map&lt;String, Integer&gt; wordCount = new HashMap&lt;&gt;();
for (String word: splitStr) {
    if (wordCount.containsKey(word)) {
        // Map already contains the word key. Just increment it's count by 1
        wordCount.put(word, wordCount.get(word) + 1);
    } else {
        // Map doesn't have mapping for word. Add one with count = 1
        wordCount.put(word, 1);
    }
}


And then simply iterate over the map, and print the key: value pair:

for (Entry&lt;String, Integer&gt; entry: map.entrySet()) {
    System.out.println("Count of : " + entry.getKey() + 
                       " in sentence = " + entry.getValue());
}