您的位置:首页 > 其它

利用Sort()方法进行排序

2017-11-06 14:15 246 查看
使用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比较器接口的调用,然后就是里面的比较项。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Sort-排序