If you don't have duplicate keys (I assume you don't) then whack the whole lot into a 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);
}
Output:
{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]
The Collection<Double>
m.values()
will be ordered as you require.
Alternatively create a wrapper class around your tuples and sort a List
of those:
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);
}
Output:
[{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
is a stable sort so this will work with duplicates and their order will not be changed.