Java8学习

Java8

函数式接口

Predicate<T>        T->boolean
     IntPredicate LongPredicate DoublePredicate

Consumer<T>      T->void
   IntConsumer LongConsumer DoubleConsumer

Function<T,R>     T->R
   IntFunction<R>
   IntToDoubleFunction
   IntToLongFunction
   LongFunction<R>
   LongToDoubleFunction
   LongToIntFunction
   DoubleFunction<T>
   ToIntFunction<R>
   ToLongFunction<T>
   ToDoubleFunction<T>
 
Supplier<T>     ()->T
   BooleanSupplier
   IntSupplier
   LongSupplier
   DoubleSupplier

UnarryOperator<T>   T->T
   IntUnaryOperator
   LongUnaryOperator
   DoubleUnaryOperator

BinaryOperator<T>    (T,T)->T
   IntBinaryOperator
   LongBinaryOperator
   DoubleBinaryOperator

BiPredicate<L,R>    (L,R)->boolean

BiConsumer<T,U>     (L,R)->void
   ObjIntConsumer<T>
   ObjLongConsumer<T>
   ObjDoubleConsumer<T>

BiFunction<T,U,R>    (T,U)->R
   ToIntBiFunction<T,U>
   ToLongBiFunction<T,U>
   ToDoubleFunction<T,U>
   

复合lambda表达式

List<Apple> list = Arrays.asList(new Apple(2), new Apple(3), new Apple(1), new Apple(4), new Apple(5));
list.sort(Comparator.comparing(Apple::getWeight));

//排序,调用Apple getWeight方法进行排序

 比较器复合

List<Apple> list = Arrays.asList(new Apple(2,"China"), new Apple(2,"Azk"), new Apple(1,"Korea"), new Apple(4,"Japan"), new Apple(5,"China"));
list.sort(Comparator.comparing(Apple::getWeight).reversed().thenComparing(Apple::getCountry));

//排序,先用重量排序,然后在反转,然后在根据国家排序

谓词复合

    public static void main(String[] args) {
        List<Apple> list = Arrays.asList(new Apple(2, "China"), new Apple(2, "Azk"), new Apple(1, "Korea"), new Apple(4, "Japan"), new Apple(5, "China"));
        list.sort(Comparator.comparing(Apple::getWeight).reversed().thenComparing(Apple::getCountry));

        Predicate<Apple> applePredicate1=(Apple apple)->apple.getWeight()>2;
        Predicate<Apple> applePredicate2= ((Predicate<Apple>) apple -> apple.getWeight() > 2).and(apple -> apple.getCountry().equals("China"));
       //筛选  苹果的重量大于2,同时属于China
    testFuHe(list,applePredicate2);   
  }
public static List<Apple> testFuHe(List<Apple> apples, Predicate<Apple> predicate) { ArrayList<Apple> as = new ArrayList<>(); for (Apple apple : apples) { if (predicate.test(apple)) { as.add(apple); } } return as; }

 函数复合

        Function<Integer,Integer> fun1=(num)->num*10;
        Function<Integer,Integer> fun2=(num)->num+10;

        Function<Integer, Integer> fun3 = fun1.andThen(fun2);       //调完fun1 在调用fun2
        Function<Integer, Integer> fun4 = fun1.compose(fun2);       //调用fun2的结果 然后在调用fun1

        Integer res3 = fun3.apply(5);
        Integer res4 = fun4.apply(5);

 流处理

流只能遍历一次。遍历完之后这个流就已经被消费掉了

流的Api

filter        中间        Stream<T>    Predicate<T>        T->boolean
map       中间     Stream<R>  Function<T,R>      T->R
limit      中间     Stream<T>
sorted     中间     Stream<T>   Compartor<T>      (T,T)->int
distinct    中间     Stream<T>
flatMap     中间     Stream<T>  Function<T,Stream<R>>  T->Stream<R>



forEach     终端            Comsumer<T>       T->void      消费每个流的元素,返回一个void
count      终端     返回流中元素的个数。
collect     终端     把流归成一个集合,比如List,Map甚至Integer

reduce     终端     Optional<T>   BinaryOperator<T>   (T,T)->T

匹配
anyMatch    终端               Predicate<T>      T->boolean        看当中是否有一个匹配
allMatch    终端               Predicate<T>      T->boolean        看当中是否全部匹配
noMatch     终端               Predicate<T>      T->boolean        确保没有匹配

查找
findAny     终端     Optional<T>              返回当前流的任意元素
findFirst    终端     Optional<T>              查找第一个

数值
sum
min
max

 案例

public class Trader {
    private String name;
    private String city;
    public Trader(String name, String city) {
        this.name = name;
        this.city = city;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getCity() {
        return city;
    }
    public void setCity(String city) {
        this.city = city;
    }
    @Override
    public String toString() {
        return "Trader{" +
                "name='" + name + '\'' +
                ", city='" + city + '\'' +
                '}';
    }
}
public class Transaction {
    private Trader trader;
    private int year;
    private int value;
    public Transaction(Trader trader, int year, int value) {
        this.trader = trader;
        this.year = year;
        this.value = value;
    }
    public Trader getTrader() {
        return trader;
    }
    public void setTrader(Trader trader) {
        this.trader = trader;
    }
    public int getYear() {
        return year;
    }
    public void setYear(int year) {
        this.year = year;
    }
    public int getValue() {
        return value;
    }
    public void setValue(int value) {
        this.value = value;
    }
}
 public static void main(String[] args) {
        Trader raoul = new Trader("Raoul", "Cambridge");
        Trader mario = new Trader("Mario", "Milan");
        Trader alan = new Trader("Alan", "Cambridge");
        Trader brian = new Trader("Brian", "Cambridge");
        List<Transaction> transactions = Arrays.asList(
                new Transaction(brian, 2011, 300),
                new Transaction(raoul, 2012, 1000),
                new Transaction(raoul, 2011, 400),
                new Transaction(mario, 2012, 710),
                new Transaction(mario, 2012, 700),
                new Transaction(alan, 2012, 950)
        );

        //找出2011年发生的所有交易,并按交易额排序(从低到高)。
        List<Transaction> res1 = transactions.stream().filter(transaction -> transaction.getYear() == 2011)
                .sorted(Comparator.comparing(Transaction::getValue)).collect(Collectors.toList());
        //交易员都在哪些不同的城市工作过?
        List<String> res2 = transactions.stream().map(transaction -> transaction.getTrader().getCity()).distinct().collect(Collectors.toList());
        //查找所有来自于剑桥的交易员,并按姓名排序。
        List<Transaction> res3 = transactions.stream().filter(transaction -> transaction.getTrader()
                .getCity().equals("Cambridge")).sorted(Comparator.comparing(o -> o.getTrader().getName())).collect(Collectors.toList());
        //返回所有交易员的姓名字符串,按字母顺序排序。
        List<String> res4 = transactions.stream().flatMap((Function<Transaction, Stream<String>>) transaction -> Stream.of(transaction.getTrader().getName()))
                .sorted().collect(Collectors.toList());
        //有没有交易员是在米兰工作的?
        Optional<Transaction> res5 = transactions.stream().filter(transaction -> transaction.getTrader().getCity().equals("Milan")).findAny();
        //打印生活在剑桥的交易员的所有交易额。
        transactions.stream().filter(transaction -> transaction.getTrader().getCity().equals("Cambridge"))
                .flatMap((Function<Transaction, Stream<?>>) transaction -> Stream.of(transaction.getValue())).forEach(System.out::println);
        //所有交易中,最高的交易额是多少?
        Optional<Transaction> res6 = transactions.stream().max(Comparator.comparingInt(Transaction::getValue));
        //找到交易额最小的交易。
        Optional<Transaction> res7 = transactions.stream().min(Comparator.comparingInt(Transaction::getValue));
    }

 构建流

由值创建流
Stream.of();
Stream<String> stringStream = Stream.of("one", "two", "three");


由数组创建流
Arrays.stream();
int[] nums={2,3,4,5,6};
IntStream stream = Arrays.stream(nums);



猜你喜欢

转载自www.cnblogs.com/xiaotao13725566749/p/9174799.html