首页 > 解决方案 > Java 集合:根据单独的键列表对值列表进行排序

问题描述

我有两个清单。键列表中的每个键对应于值列表中的一个值。假设这两个列表大小相同。我需要根据键列表对两个列表进行排序。

我尝试了以下方法,但显然它不起作用,因为它会弄乱键值关联。除了编写自己的排序实现之外,我只是不知道还能做什么。

// Would mess up the key-value associations
    public void sort() {
        Collections.sort(this.keys);
        Collections.sort(this.values);
    }

    /* Example: 
        this.keys = (2, 1, 4)
        this.values = ("value for 2", "value for 1", "value for 4")
        this.sort()
        this.keys = (1, 2, 4)
        this.values = ("value for 1", "value for 2", "value for 4") */

有没有一种简单的方法可以做到这一点?我宁愿坚持使用内置的排序功能,而不是自己编写。我也不能改变底层的数据结构。

标签: javalist

解决方案


如果如您所说,您需要保留两个列表,则可以尝试以下操作:

// Create a map that orders its data.
Map<Integer, String> tmp = new TreeMap<>();

// Put your data into this structure and let it sort the data for you.
for (int i=0; i<keys.size(); i++) {
    tmp.put(keys.get(i), values.get(i));
}

// Clear your original lists.
keys.clear()
values.clear();

// Put the data back into your lists - but sorted this time.
for (Integer key : tmp.keySet()) {
    keys.add(key);
    values.add(tmp.get(key));
}

推荐阅读