Answers for "java how to put a string sentence in a map"

0

java how to put a string sentence in a map

Map < String, Integer > map = new HashMap < > (); 
  Scanner sc = new Scanner(System.in); // used to read user input
  System.out.println("Enter a string:");
  String sentence = sc.nextLine();

  String[] tokens = sentence.split(" "); // split based on space

  for (String token: tokens) {

   String word = token.toLowerCase(); // case insensitive
   if (map.containsKey(word)) {
    int count = map.get(word); // get word count 
    map.put(word, count + 1); // override word count
   } else {
    map.put(word, 1); // initial word count to 1
   }
  }
Posted by: Guest on March-19-2020

Code answers related to "java how to put a string sentence in a map"

Code answers related to "Java"

Java Answers by Framework

Browse Popular Code Answers by Language