提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
程序统计字符串中每个单词出现的次数。
import java.util.HashMap; import java.util.Map; /*来自 N o w J a v a . c o m*/ import java.util.Set; import java.util.TreeSet; public class Main { public static void main(String[] args) { Map<String, Integer> myMap = new HashMap<>(); createMap(myMap); // create map based on user input displayMap(myMap); // display map content } private static void createMap(Map<String, Integer> map) { String input = "this is a test this is a test"; String[] tokens = input.split(" "); // processing input text for (String token : tokens) {/*时 代 J a v a - nowjava.com*/ String word = token.toLowerCase(); // get lowercase word // if the map contains the word if (map.containsKey(word)) // is word in map { int count = map.get(word); // get current count map.put(word, count + 1); // increment count } else map.put(word, 1); // add new word with a count of 1 to map } } // display map content private static void displayMap(Map<String, Integer> map) { Set<String> keys = map.keySet(); // get keys // sort keys TreeSet<String> sortedKeys = new TreeSet<>(keys); System.out.pr