Java按某些键的值排序映射

时间:2018-05-28 04:35:21

标签: java sorting comparator

如何实施Comparator按某些键值对地图列表进行排序?我的目标是任意排序两个列表,以便我可以比较不属于排序的其他字段。

例如,假设我有这两个地图列表,我想按firstName和lastName排序。

+-----------+--------+-------+-------+
| List 1    | Map 1  | Map 2 | Map 3 |
+-----------+--------+-------+-------+
| firstName | John   | Eric  | John  |
| lastName  | Miller | Smith | Davis |
| age       | 17     | 19    | 35    |
+-----------+--------+-------+-------+

+-----------+--------+-------+-------+
|  List 2   | Map 1  | Map 2 | Map 3 |
+-----------+--------+-------+-------+
| firstName | Eric   | John  | John  |
| lastName  | Smith  | Davis | Miller|
| age       | 53     | 38    | 26    |
+-----------+--------+-------+-------+

在我对其进行排序之后,现在我可以将列表1的地图1与列表2的地图2进行比较,看看它们有什么不同。

所以我有一个实现比较器的类,如下所示:

// Note that the values may not implement Comparable
public class PersonComparator implements Comparator<Map<String, Object>> {
    private List<String> sortKeys = Arrays.asList("firstName", "lastName");

    @Override
    public int compare(Map<String, Object> map1, Map<String, Object> map2) {
        Map<String, Object> keyValue1 = new HashMap<>();
        sortKeys.forEach(key -> keyValue1.put(key, map1.get(key)));

        Map<String, Object> keyValue2 = new HashMap<>();
        sortKeys.forEach(key -> keyValue2.put(key, map2.get(key)));

        return keyValue2.hashCode() - keyValue1.hashCode();
    }
}

在每个列表上调用sort将导致以下结果:

+-----------+--------+-------+-------+
| List 1    | Map 1  | Map 2 | Map 3 |
+-----------+--------+-------+-------+
| firstName | John   | Eric  | John  |
| lastName  | Miller | Smith | Davis |
| age       | 17     | 19    | 35    |
+-----------+--------+-------+-------+

+-----------+--------+-------+-------+
| List 2    | Map 1  | Map 2 | Map 3 |
+-----------+--------+-------+-------+
| firstName | John   | Eric  | John  |
| lastName  | Miller | Smith | Davis |
| age       | 26     | 53    | 38    |
+-----------+--------+-------+-------+

但是列表的顺序永远不会改变......我做错了什么?

1 个答案:

答案 0 :(得分:0)

最终,您的排序基于密钥的哈希码 - 一种不一定与其值相关的排序(即,“较小”字符串可以具有较大的哈希码,反之亦然)。

相反,您应该根据值本身进行排序,即使它意味着明确地将您拥有的ls值转换为可比较的值:

Object