利用Sort()方法进行排序

使用Sort()方法,就需要使用到Comparator比较器,但是他的写法有多种

  • 直接调用Collections.sort()方法,其中list为要排序的集合,new Comparator()为迭代器与比较方法。
List<String> list = new ArrayList<String>(); 
Collections.sort(list, new Comparator() {
     public int compare(final Object a, final Object b) {
          final Object arra = (Object) a;
          final Object arrb = (Object) b;
          final int one = Integer.parseInt(arra  + "");
          final int two = Integer.parseInt(arrb  + "");
          return two - one;
     }
});
  • 当要比较的集合是实体类时,可以实现实现IComparable接口
public class A implements Comparable<A>{
    /** 序号 **/
    private int num;
    /**要点提示**/
    private String tip;

    public int getNum() {
        return num;
    }
    public void setNum(int num) {
        this.num = num;
    }
    public String getTip() {
        return tip;
    }
    public void setTip(String tip) {
        this.tip = tip;
    }
    @Override
    public int compareTo(A other) {
          final int one = this.getNum();
          final int two = other.getNum();
          return two - one;
    }
}
List<A> list = new ArrayList<A>(); 
list.Sort();
  • 针对hashMap的key,value进行排序
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("d", 2);
map.put("c", 1);
map.put("b", 1);
map.put("a", 3);

List<Map.Entry<String, Integer>> infoIds =
    new ArrayList<Map.Entry<String, Integer>>(map.entrySet());

//排序前
for (int i = 0; i < infoIds.size(); i++) {
    String id = infoIds.get(i).toString();
    System.out.println(id);
}
//d 2
//c 1
//b 1
//a 3

//排序
Collections.sort(infoIds, new Comparator<Map.Entry<String, Integer>>() {   
    public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {      
        //return (o2.getValue() - o1.getValue()); 
        return (o1.getKey()).toString().compareTo(o2.getKey());
    }
}); 

//排序后
for (int i = 0; i < infoIds.size(); i++) {
    String id = infoIds.get(i).toString();
    System.out.println(id);
}
//根据key排序
//a 3
//b 1
//c 1
//d 2
//根据value排序
//a 3
//d 2
//b 1
//c 1

总结,以上就是利用Sort()进行相关排序的问题,值得注意的就是IComparable比较器接口的调用,然后就是里面的比较项。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值