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

时间:2020-05-22 17:07:24   收藏:0   阅读:49
 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

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!