方式一(比较繁琐)
public static void hashMapMethod1(){
Scanner scan = new Scanner(System.in);
System.out.println("hashMapMethod1 Please input String :");
String user_input = scan.next();
HashMap<Character,Integer> hashMap_var = new HashMap<>();
Integer integer_num = 0;
// String to charArray
// 将字符串转换为字符数组
char[] user_input_charArray = user_input.toCharArray();
for (int i = 0; i < user_input_charArray.length; i++) {
//判断 ashMap_var 的 key 键中是否有 i 索引下的字符存在
if (hashMap_var.containsKey(user_input_charArray[i])){
//存在,则取出 hashMap_var 中的key键所对应的值,并+1
integer_num = hashMap_var.get(user_input_charArray[i]);
integer_num++;
// 自增完成后,存入对应的键值对
hashMap_var.put(user_input_charArray[i],integer_num);
}else {
// 不存在,则,以不存在的字符为键,1为值,存入键值对
hashMap_var.put(user_input_charArray[i],1);
}
}
System.out.println(hashMap_var);
}
方式二(还是繁琐)
public static void hashMapMethod2(){
HashMap<Character,Integer> hashMap_count = new HashMap<>();
Scanner scan = new Scanner(System.in);
System.out.println("hashMapMethod2 Please input String :");
String user_input_String = scan.next();
// foreach遍历字符数组
for (Character character : user_input_String.toCharArray()) {
if (hashMap_count.containsKey(character)){
// 存在,取值 + 1 ,放入对应的键值对
Integer integer_num = hashMap_count.get(character);
integer_num++;
hashMap_count.put(character,integer_num);
}else {
// 不存在,不存在的字符为键,1为值,存入键值对
hashMap_count.put(character,1);
}
}
System.out.println(hashMap_count);
}
结果如下
// give the result follows
方式三(利用lambda表达式)
两种写法原理一样 < 在下面代码中,这里面是注释,不然看不清 >
public static void main1(String[] args) {
< 将字符串转换为字符串数组 >
String[] str = "If you want to change your fate l think you must come to the dark horse to learn java".split(" ");
< 创建一个容器,用与接受字符串及其数量 >
HashMap<String, Integer> hashMap = new HashMap<>();
for (String s : str){
< 判断当前字符在hashMap容器中是否存在,存在则数量+1 >
if (hashMap.containsKey(s)) {
hashMap.put(s, hashMap.get(s) + 1);
} else {
< 反之不存在,则将当前的字符串作为key存入,1作为数量存入当前key所对应的value >
hashMap.put(s, 1);
}
}
System.out.println(hashMap);
}
public static void main(String[] args) throws Exception {
List<String> strings = Arrays.asList("If you want to change your fate l think you must come to the dark horse to learn java".split(" "));
HashMap<String, Integer> map = new HashMap<>();
strings.forEach(e -> map.put(e, map.containsKey(e) ? map.get(e) + 1 : 1));
map.entrySet().forEach(System.out::println);
}