每日一經(jīng)
每天收集一個(gè)java日常能用到的解決問題的方法婴栽,以后方便查閱。
實(shí)現(xiàn)
java8環(huán)境爱谁,使用了Arrays.sort和lambda表達(dá)式:
/**
* 瓜類:
* 類型和重量
*/
public class Melon {
private String type;
private Integer weight;
public Melon(String type, int weight) {
this.type = type;
this.weight = weight;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public int getWeight() {
return weight;
}
public void setWeight(Integer weight) {
this.weight = weight;
}
}
排序
Melon[] melons = new Melon[3];
melons[0] = new Melon("1 melon", 1);
melons[1] = new Melon("10 melon", 10);
melons[2] = new Melon("5 melon", 5);
// before
for (Melon melon: melons) {
System.out.println(melon.getType());
}
// asc sort
Arrays.sort(melons, (Melon melon1, Melon melon2)
-> Integer.compare(melon1.getWeight(), melon2.getWeight()));
// after
for (Melon melon: melons) {
System.out.println(melon.getType());
}
// desc sort
Arrays.sort(melons, (Melon melon1, Melon melon2)
-> Integer.compare(melon2.getWeight(), melon1.getWeight()));
// after
for (Melon melon: melons) {
System.out.println(melon.getType());
}