每日一经
每天收集一个java日常能用到的解决问题的方法,以后方便查阅。
实现
java8环境,使用了Arrays.sort和lambda表达式:
/**
* 瓜类:
* 类型和重量
*/
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());
}