java how to put a string sentence in a map

Solutions on MaxInterview for java how to put a string sentence in a map by the best coders in the world

showing results for - "java how to put a string sentence in a map"
Leonardo
24 Jun 2016
1Map < String, Integer > map = new HashMap < > (); 
2  Scanner sc = new Scanner(System.in); // used to read user input
3  System.out.println("Enter a string:");
4  String sentence = sc.nextLine();
5
6  String[] tokens = sentence.split(" "); // split based on space
7
8  for (String token: tokens) {
9
10   String word = token.toLowerCase(); // case insensitive
11   if (map.containsKey(word)) {
12    int count = map.get(word); // get word count 
13    map.put(word, count + 1); // override word count
14   } else {
15    map.put(word, 1); // initial word count to 1
16   }
17  }