You define a Holder class to save the character-number mapping, then sort all Holders according to the numbers in the Holders from large to small, and finally output the characters of each Holder in order.
import java.util.Arrays;
public class Test {
static class Holder implements Comparable<Holder> {
public int num;
public String str;
public Holder(String str, int num) {
this.str = str;
this.num = num;
}
@Override
public int compareTo(Holder that) {
return that.num - this.num; // 逆序排序
}
}
public static void test(String[] strs, int[] nums) {
if (strs.length != nums.length) {
return;
}
Holder[] holders = new Holder[strs.length];
for (int i = 0; i < strs.length; i++) {
holders[i] = new Holder(strs[i], nums[i]);
}
Arrays.sort(holders);
for (Holder holder : holders) {
System.out.print(holder.str + " ");
}
System.out.println();
}
public static void main(String[] args) throws Exception {
String[] strs = {"A", "B", "C", "D", "E", "F", "G", "H"};
int[] a = {3, 2, 6, 4, 8, 9, 1, 23};
test(strs, a);
}
}
You define a Holder class to save the character-number mapping, then sort all Holders according to the numbers in the Holders from large to small, and finally output the characters of each Holder in order.
Run results: