在网上看到的一道题,这里主要是记录一下
题目:给定一个hashMap,存储了若干个(name,age)这样的键值对,按照年龄进行排序,打印出姓名。
方法一(网上看到的):
public static void sortByageprintName(Map<String,Integer> map){
//创建一个集合数组,存放每一个年龄的姓名,假设人的年龄处于0-100岁
List<String>[]array =new List[101];
//遍历出每一个键(姓名)
for (String name:map.keySet()) {
//获取键所对应的值
int age =map.get(name);
if(array[age]==null){
array[age]=new LinkedList<>();
}
array[age].add(name);
}
for (int i=0;i<array.length;i++){
if(array[i]!=null){
System.out.println(i+" :"+array[i]);
}
}
}
方法二:
public static void sortByageprintName02(Map<String,Integer> map) {
Set<Map.Entry<String,Integer>> entrySet=map.entrySet();
//创建一个TreeSet集合存储去重后的排序的age
TreeSet<Integer> treeSet=new TreeSet<>();
//创建一个LinkedList集合存储每一个entry对象
List<Map.Entry<String,Integer>> entryList=new LinkedList<>();
for(Map.Entry<String,Integer> e :entrySet){
//获取所有的entry对象
entryList.add(e);
//去重后排好序的age
treeSet.add(e.getValue());
}
List<Integer> list =new LinkedList<>(treeSet);
for(int i=0;i<list.size();i++){
int age=list.get(i);
//存储这个年龄的姓名
System.out.print(age+":");
List<String> list2=new ArrayList<>();
for(int j=0;j<entryList.size();j++){
if (entryList.get(j).getValue().equals(age)){
list2.add(entryList.get(j).getKey());
}
}
System.out.println(list2);
}
}
测试
public static void main(String[] args) {
Map<String,Integer> map =new HashMap<>();
map.put("张三",25);
map.put("李四",20);
map.put("王五",20);
map.put("赵六",18);
map.put("码云",30);
map.put("github",30);
map.put("csdn",35);
map.put("postman",28);
map.put("eolinker",28);
sortByageprintName(map);
System.out.println("----------------------");
sortByageprintName02(map);
}
测试打印结果:
18 :[赵六]
20 :[李四, 王五]
25 :[张三]
28 :[eolinker, postman]
30 :[github, 码云]
35 :[csdn]
----------------------
18:[赵六]
20:[李四, 王五]
25:[张三]
28:[eolinker, postman]
30:[github, 码云]
35:[csdn]