繁体   English   中英

Java集合:根据单独的键列表对值列表进行排序

[英]Java collections: Sorting a list of values according to a separate list of keys

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

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

// 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") */

有没有简单的方法可以做到这一点? 我宁愿使用内置的sort函数,而不是编写自己的函数。 我也不能更改基础数据结构。

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

// 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));
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM