import java.util.*;public class CountOccurrenceOfWords { public static void main(String[] args) { String text = "Good morning. Have a good class. " + "Have a good visit. Have fun!"; TreeMap map = new TreeMap(); String[] words = text. ("[ \n\t\r.,;:!?(){}]"); for (int i = 0; i < words.length; i++) { String key = words[i].toLowerCase(); if (words[i].length() > 1) { if (map.get(key) == null) { map.put(key, 【2】 ); } else { int value = map.get(key). ; value++; map.put(key, value); } } } Set> entrySet = map. ; for (Map.Entry entry: entrySet){ System.out.println(entry.getValue() + "\t" + entry.getKey()); } System.out.println("-----------------"); for(Object key:map. ) { System.out.println( map.get(key)+ ":"+key ); } System.out.println("---------------"); entrySet.forEach( -> System.out.println(e.getValue() + "\t" + e.getKey())); System.out.println("---------------"); map.forEach( -> { System.out.println(value + ":" + key); }); } }
发布时间:2024-03-31 20:56:24