发现很多年前写的东东,好玩
package com.felee.feadmin.demo.controller;
import java.util.HashMap;
import java.util.Map;
public class TestSort {
/**
* 要求在一篇文章中 打印出所有单词的个数 * 例如:输入:apple banana is hello is apple hello * 打印结果:apple 2 * banana 1 * is 2 * hello 2
*/
public static void main(String[] args) {
String input = "apple banana apple is banana is hello is apple hello";
Map<String, Integer> map = new HashMap<String, Integer>();
String[] str = input.split(" ");//以空格截取字符串,放到数组中
for (String danci : str) {
if (danci.trim().length() == 0) {
continue;
}
if (map.containsKey(danci.trim()))//如果此映射包含指定键的映射关系,则返回 true。
{
int count = map.get(danci.trim());
map.put(danci.trim(), count + 1);
} else {
map.put(danci.trim(), 1);
}
}
System.out.println(map.size());//返回集合中有多少映射关系
System.out.println(map.values()); //返回此映射中包含的值
System.out.println(map.keySet());//返回此映射中包含的键
System.out.println(map.entrySet());//返回此映射中包含的映射关系
for (Map.Entry<String, Integer> entity : map.entrySet()) {
System.out.println(entity.getKey() + " " + entity.getValue());
}
}
}