身高排序

题目

给你一个字符串数组names,和一个由互不相同 的正整数组成的数组heights.两个数组的长度均为n.对每个下标 i,name[i]和heights[i] 表示第i个人的名字和身高.降序返回对应的名字数组names.

思路

在 HashMap 中存储了身高和人名信息。接下来,利用 entrySet() 方法获取映射关系集合,并将这个集合转换成 List 类型的 entryList。接着调用了 Collections.sort() 方法来对 entryList 进行排序。通过 getKey() 和 getValue() 方法分别获取身高和人名信息,最终按照从小到大排序存储到字符串数组 result 中并返回。

class Solution {
public String[] sortPeople(String[] names, int[] heights) {
HashMap<Integer,String> storage = new HashMap<Integer,String>();
int length = names.length;
for(int i = 0;i<length;i++){
storage.put(Integer.valueOf(heights[i]),names[i]); // 将身高和对应的人名信息存储到 HashMap 中
}

// 排序 HashMap,输出结果
List<Map.Entry<Integer, String>> entryList = new ArrayList<Map.Entry<Integer, String>>(storage.entrySet());
Collections.sort(entryList, new Comparator<Map.Entry<Integer, String>>() {
@Override
public int compare(Map.Entry<Integer, String> o1, Map.Entry<Integer, String> o2) {
return o2.getKey() - o1.getKey();
}
});

String[] result = new String[length];
int i = 0;
for (Map.Entry<Integer, String> entry : entryList) {
result[i++] = entry.getValue();
}
return result;
}
}

Collections是怎么对List里面的Map进行排序的.

  1. Collections.sort()方法可以对实现Comparable接口或使用自定义比较器Comparator的类进行排序.由于List中的元素是Map,我们需要使用Comparator来指定排序规则.
    如:
    List<Map<String, Object>> listMap = new ArrayList<>();
    Map<String, Object> map1 = new HashMap<>();
    map1.put("name", "张三");
    map1.put("age", 25);
    listMap.add(map1);

    Map<String, Object> map2 = new HashMap<>();
    map2.put("name", "李四");
    map2.put("age", 20);
    listMap.add(map2);

    Map<String, Object> map3 = new HashMap<>();
    map3.put("name", "王五");
    map3.put("age", 30);
    listMap.add(map3);

    // 使用匿名内部类 Comparator 进行排序
    Collections.sort(listMap, new Comparator<Map<String, Object>>() {
    @Override
    public int compare(Map<String, Object> o1, Map<String, Object> o2) {
    int age1 = (int) o1.get("age");
    int age2 = (int) o2.get("age");
    return age1 - age2; // 正序排列
    // return age2 - age1; // 倒序排列
    }
    });

    // 输出结果
    for (Map<String, Object> map : listMap) {
    System.out.println(map.get("name") + ":" + map.get("age"));
    }