Map两种遍历方式
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* Created by jiaobuchong on 1/24/16.
*/
public class CountChNums {
public static void main(String[] args) {
String[] a = {"a", "b", "a", "b", "c", "a", "b", "c", "b"};
Map<String, Integer> countNums = new HashMap<>();
for (int i = 0; i < a.length; i++) {
//key 为字符, value为字符出现的次数
if (countNums.containsKey(a[i])) {
int temp = countNums.get(a[i]);
countNums.replace(a[i], temp + 1);
} else {
countNums.put(a[i], 1);
}
}
/**
* Map两种遍历方式
* 方式1
*/
Set<Map.Entry<String, Integer>> entrySet = countNums.entrySet();
for (Map.Entry<String, Integer> entry : entrySet) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
System.out.println();
/**
* 方式2 现获取所有的key的集合
*/
Set<String> set = countNums.keySet();
for (String key : set) {
System.out.println(key + ": " + countNums.get(key));
}
}
}
Map栗1
贴上另外一个例子,以作对比:
/*
* 输入:Shall I Compare Thee To Summer's Day ddd
* 结果:'(1)C(1)D(1)I(1)S(2)T(2)a(3)d(3)e(4)h(2)l(2)m(3)o(2)p(1)r(2)s(1)u(1)y(1)
*/
public class TreeMapDemo {
public static void main(String[] args) {
// 定义一个字符串(可以改进为键盘录入)
Scanner sc = new Scanner(System.in);
System.out.println("请输入一个字符串:");
String line = sc.nextLine().replaceAll(" +", ""); //并去掉所有空格
// 定义一个TreeMap集合,可以按照字符的先后顺序输出
TreeMap<Character, Integer> tm = new TreeMap<Character, Integer>();
//把字符串转换为字符数组
char[] chs = line.toCharArray();
//遍历字符数组,得到每一个字符
for(char ch : chs){
//拿刚才得到的字符作为键到集合中去找值,看返回值
Integer i = tm.get(ch);
//是null:说明该键不存在,就把该字符作为键,1作为值存储
if(i == null){
tm.put(ch, 1);
}else {
//不是null:说明该键存在,就把值加1,然后重写存储该键和值
i++;
tm.put(ch,i);
}
}
//定义字符串缓冲区变量
StringBuilder sb= new StringBuilder();
//遍历集合,得到键和值,进行按照要求拼接
Set<Character> set = tm.keySet();
for(Character key : set){
Integer value = tm.get(key);
sb.append(key).append("(").append(value).append(")");
}
//把字符串缓冲区转换为字符串输出
String result = sb.toString();
System.out.println("result: "+result);
}
}
Map栗2
获取List中重复元素的个数,按map的value进行排序
import java.util.*;
public class ListEleCount {
public static void main(String[] args) {
List<String> names = new ArrayList<>();
names.add("jack");
names.add("jack");
names.add("jack");
names.add("tom");
names.add("tom");
names.add("lily");
names.add("jiaobuchong");
names.add("ijiaobu");
names.add("ijiaobu");
names.add("ijiaobu");
names.add("ijiaobu");
names.add("ijiaobu");
/**
* 统计这个list中重复元素的个数 并按个数降序输出
*/
Map<String, Integer> count = new HashMap<>();
for (String name : names) {
if (count.keySet().contains(name)) {
count.put(name, count.get(name) + 1);
} else {
count.put(name, 1);
}
}
// 排序
System.out.println(count);
List<Map.Entry<String, Integer>> dataList = new ArrayList<>(count.entrySet());
Collections.sort(dataList, new Comparator<Map.Entry<String, Integer>>() {
@Override
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
return o2.getValue() - o1.getValue();
}
});
System.out.println(dataList);
}
}