import static java.util.Comparator.comparing;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
public class SortAppleLambda {
public static void main(String args[]) {
List<Apple> inventory = new ArrayList<>();
inventory.add(new Apple(new BigDecimal("0.2")));
inventory.add(new Apple(new BigDecimal("0.33")));
inventory.add(new Apple(new BigDecimal("0.25")));
inventory.add(new Apple(new BigDecimal("0.19"),"a"));
inventory.add(new Apple(new BigDecimal("0.19"),"b"));
inventory.add(new Apple(new BigDecimal("0.3")));
System.out.println("原样输出:"+inventory);
//排序 方法1
// inventory.sort((a1,a2) -> a1.getWeight().compareTo(a2.getWeight()));
// 使用lambda表达式,直接写实现类的方法参数和方法体,
//排序 方法2, import static java.util.Comparator.comparing
inventory.sort(comparing(apple -> apple.getWeight()));
// 比较器复合 Apple::getWeight方法引用,只写方法名不加后面的()
inventory.sort(comparing(Apple::getWeight)); // 正序
inventory.sort(comparing(Apple::getWeight).reversed()); // 倒序
inventory.sort(comparing(Apple::getWeight).reversed() // 倒序
.thenComparing(Apple::getCountry)); // 两个苹果一样重的时候再按国家排序,默认正序,也可以.thenComparing(Apple::getCountry).reversed())倒序
// Comparator中有一个静态方法comparing(),可以用来进一步简化Lambda表达式(PS: java 8之前是不支持接口中包含静态方法的,java中为了支持Lambda表达式,接口中已经支持静态方法)
// static <T, U> Comparator<T> comparing(...)
// 排序后
System.out.println("排序后为:"+inventory);
inventory.forEach(apple -> System.out.println(apple.getWeight()+"***"+apple.getCountry()));
// 小插曲复合操作
Function<Integer, Integer> f1 = x -> x+1;
Function<Integer, Integer> f2 = x -> x*2;
// 复合操作就是先计算x+1之后用得出后的结果再乘2所以得4
Function<Integer, Integer> h = f1.andThen(f2);
// 传入参数1,先计算x+1
int result = h.apply(1);
System.out.println(result);
}
}
class Apple {
private BigDecimal weight;
private String country;
public Apple(BigDecimal weight) {
this.weight = weight;
}
public Apple(BigDecimal weight, String country) {
this.weight = weight;
this.country = country;
}
public BigDecimal getWeight() {
return weight;
}
public void setWeight(BigDecimal weight) {
this.weight = weight;
}
public String toString() {
return this.weight + "";
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
java8排序
最新推荐文章于 2023-03-08 10:51:18 发布
903

被折叠的 条评论
为什么被折叠?



