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.printf("%nMap contains:%nKey\t\tValue%n");
/**代码未完, 请加载全部代码(NowJava.com).**/
本文系作者在时代Java发表,未经许可,不得转载。如有侵权,请联系nowjava@qq.com删除。