如果您没有重复的密钥(我假设您没有),那么将整个密钥敲入一个TreeMap
:
public static void main(String[] args) throws Exception {
int[] keys = new int[]{7, 9, 4, 2, 8, 5, 6, 0};
double[] vals = new double[]{10, 31, 20, 22, 21, 30, 33, 34};
final Map<Integer, Double> m = new TreeMap<>();
for (int i = 0; i < keys.length; ++i) {
m.put(keys[i], vals[i]);
}
System.out.println(m);
}
输出:
{0=34.0, 2=22.0, 4=20.0, 5=30.0, 6=33.0, 7=10.0, 8=21.0, 9=31.0}
[34.0, 22.0, 20.0, 30.0, 33.0, 10.0, 21.0, 31.0]
将Collection<Double>
m.values()
根据您的需要订购。
或者,围绕您的元组创建一个包装类并对其中的一个List
进行排序:
public static void main(String[] args) throws Exception {
int[] keys = new int[]{7, 9, 4, 2, 8, 5, 6, 0};
double[] vals = new double[]{10, 31, 20, 22, 21, 30, 33, 34};
final class Wrapper implements Comparable<Wrapper> {
final int key;
final double value;
public Wrapper(int key, double value) {
this.key = key;
this.value = value;
}
@Override
public int compareTo(Wrapper o) {
return Integer.compare(key, o.key);
}
@Override
public String toString() {
return "{key=" + key + ", value=" + value + "}";
}
}
final List<Wrapper> wrappers = new ArrayList<>(keys.length);
for (int i = 0; i < keys.length; ++i) {
wrappers.add(new Wrapper(keys[i], vals[i]));
}
Collections.sort(wrappers);
System.out.println(wrappers);
}
输出:
[{key=0, value=34.0}, {key=2, value=22.0}, {key=4, value=20.0}, {key=5, value=30.0}, {key=6, value=33.0}, {key=7, value=10.0}, {key=8, value=21.0}, {key=9, value=31.0}]
Collections.sort
是一种稳定的排序,因此这将适用于重复项,并且它们的顺序不会改变。