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);


文件生成流
Stream<String> lines = Files.lines(Paths.get("xxx.txt"), Charset.defaultCharset());


無限生成流
Stream.iterate(1, integer -> integer+1).limit(10).forEach(System.out::println);    //每一個新值都是依照上一次的值按規則生成的
Stream.generate(Math::random).limit(10).forEach(System.out::println);

收集器 

預約義收集器

transactions.stream().map(transaction -> transaction.getValue()).collect(Collectors.counting());  // Collectors.counting()統計個數

transactions.stream().collect(Collectors.maxBy(Comparator.comparingInt(Transaction::getValue)));   // Collectors.maxBy()  取最大值

transactions.stream().collect(Collectors.summingInt(Transaction::getValue));        //求和

transactions.stream().collect(Collectors.averagingInt(Transaction::getValue));        //求平均

transactions.stream().map(transaction -> transaction.getTrader().getName()).collect(Collectors.joining(","));    //字符串拼接

 分組

 transactions.stream().collect(Collectors.groupingBy(new Function<Transaction, Integer>() {
     @Override
     public Integer apply(Transaction transaction) {
          return transaction.getYear();
       }
     }));

transactions.stream().collect(Collectors.groupingBy(Transaction::getYear));    //按年限分組
 

//多級分組
Map<Integer, Map<String, List<Transaction>>> re2 = transactions.stream().collect(Collectors.groupingBy(Transaction::getYear, Collectors.groupingBy((Transaction transaction) -> transaction.getTrader().getCity())));
Map<Integer, Map<String, List<Transaction>>> re3 = transactions.stream().collect(Collectors.groupingBy(Transaction::getYear, Collectors.groupingBy(new Function<Transaction, String>() {
@Override
public String apply(Transaction o) {
return o.getTrader().getCity();
}
})));


//注意
groupingBy收集器傳遞給外層收集器來實現堆積分組。進一步說傳遞給第一個groupingBy的第二個收集器能夠是任何類型,而不必定是另外一個groupingBy
Map<Integer, Long> count = transactions.stream().collect(Collectors.groupingBy(Transaction::getYear, Collectors.counting()));

將收集好的結果轉換爲另外一種類型
Map<Integer, Transaction> re4 = transactions.stream().collect(Collectors.groupingBy(Transaction::getYear, Collectors.collectingAndThen(Collectors.maxBy(Comparator.comparing(Transaction::getValue)), Optional::get)));
相關文章
相關標籤/搜索