java topn_topN排序问题求解。

你定义一个 Holder 类,用来保存 字符-数字 这个映射,然后对所有的 Holder,按照 Holder 中的数字从大到小排序,最后按序输出每个 Holder 的字符。

import java.util.Arrays;

public class Test {

static class Holder implements Comparable {

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

}

}

运行结果:

389091ccb19f16de10a43f9c532359b7.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值