java8排序

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;
   }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值