码迷,mamicode.com
首页 > 编程语言 > 详细

[20-05-22][Thinking in Java 37]Java Container 9 - Map - 2

时间:2020-05-22 17:07:24      阅读:49      评论:0      收藏:0      [点我收藏+]

标签:The   container   apt   char   ati   method   设置   null   for   

 1 package test_19_3;
 2 
 3 import java.util.HashMap;
 4 import java.util.Map;
 5 
 6 public class MapTest {
 7 
 8     public static void main(String[] args) {
 9         
10         Map<String, Integer> vowels = new HashMap<String, Integer>();
11                 
12         String str = "trying to create a method to count the vowels";
13         
14         char[] chArr = str.toCharArray();
15         
16         for (int i = 0; i < chArr.length; i++) {
17             Integer count = vowels.get(chArr[i] + "");
18             // 键对应的值,不存在则创建并设置值为1,已存在则值加1
19             vowels.put(chArr[i] + "", count == null ? 1 : count + 1);
20         }
21         
22         System.out.println("a : " + vowels.get("a"));
23         System.out.println("e : " + vowels.get("e"));
24         System.out.println("i : " + vowels.get("i"));
25         System.out.println("o : " + vowels.get("o"));
26         System.out.println("u : " + vowels.get("u"));
27         
28     }
29 }

 

结果如下:

a : 2
e : 5
i : 1
o : 5
u : 1

[20-05-22][Thinking in Java 37]Java Container 9 - Map - 2

标签:The   container   apt   char   ati   method   设置   null   for   

原文地址:https://www.cnblogs.com/mirai3usi9/p/12937961.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!