Java8實戰,

 

Supplier

1,java

@FunctionalInterface
public interface Supplier<T> {編程

2,    T get();併發

3,app

Supplier<Apple> c1 = Apple::new
Apple a1 = c1.get();函數

 consumer接口

1,優化

@FunctionalInterface
public interface Consumer<T> {blog

2,void accept(T t);接口

3,主要用來輸出的ip

 

function 接口

1,public interface Function<T, R> {資源

2,T apply(F input);

3,主要是用來轉換東西的

4,函數複合,

  • andThen    f.andThen(g)    數學上會寫做g(f(x))
  • compose   f.compose(g);   數學上會寫做f(g(x))

Predicate接口

1,充當一個參數化的返回Boolean比較方法

2,public interface Predicate<T> {

3,boolean test(T t);

4,能動態替換返回boolean的函數

5,基本類型裝箱問題,

DoublePredicate
boolean test(double value);//有對應的原始類型特化接口

 

 6,謂詞複合,優先級從左到右a.or(b).and(c)  ==  (a || b )&& c

  • negate()
  • and()
  • or()

 

lambda用法

1,

2,

3,

4,基本lambda語法

 

5,基本用法

6,在面向資源編程的lambda,不須要重複打開資源和關閉資源

7,lambda也有匿名函數的問題

8,方法引用

  • 靜態方法引用,(例如Integer的parseInt方法,寫做Integer::parseInt)。
  • 實例方法引用,(例如String的length,String::length
  • 方法體裏面的方法引用,進一步的方法引用

        

 

 

 9,比較器複合

  • 翻轉:list.sort(comparing(Object::getXXX).reveserd());
  • 一樣的時候添加第二個比較器,第二個是comparator類型, list.sort(Comparator.comparing(Integer::intValue).reversed().thenComparing(Integer::compareTo));

 

 

 

 

 stream

1,更加簡單的利用多cpu

 

 

2,基本概念

 流是「從支持數據處理操做的源生成的一系列元素」。
 流利用內部迭代:迭代經過filter、map、sorted等操做被抽象掉了。
 流操做有兩類:中間操做和終端操做。
 filter和map等中間操做會返回一個流,並能夠連接在一塊兒。能夠用它們來設置一條流 水線,但並不會生成任何結果。
 forEach和count等終端操做會返回一個非流的值,並處理流水線以返回結果。  流中的元素是按需計算的。
3,filter,篩選和切片
4,limit,skip
5,map,映射
  • flatMap
  •  

6,查找和匹配

  • anyMatch方法返回一個boolean,所以是一個終端操做。 
    if(menu.stream().anyMatch(Dish::isVegetarian)){
    System.out.println("The menu is (somewhat) vegetarian friendly!!"); }  

  • allMatch方法的工做原理和anyMatch相似,但它會看看流中的元素是否都能匹配給定的謂
  boolean isHealthy = menu.stream().allMatch(d -> d.getCalories() < 1000); 
  • 和allMatch相對的是noneMatch。
  boolean isHealthy = menu.stream()

  .noneMatch(d -> d.getCalories() >= 1000);  

  • findFirst和findAny

7,歸約

  • reduce , 
    累加:int sum = numbers.stream().reduce(0, Integer::sum);

   最大最小值:Optional min = numbers.stream().reduce(Integer::min);  

8,併發的有狀態和無狀態

9,優化自動裝箱,

  • int calories = menu.stream()  .mapToInt(Dish::getCalories)  .sum();
  • 自動裝箱

    IntStream intStream = menu.stream().mapToInt(Dish::getCalories)
    Stream<Integer> stream = intStream.boxed();

 10,小結

11,collect

 

 

 

 

Java8其餘

1,default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {

   能夠添加默認實現

2,在 java8 中的接口中不只增長了默認方法,還增長了靜態方法。使用方式接口名.方法名。

3,

@FunctionalInterface
public interface Runnable {代表是個函數接口

Java8重構小實例

1,策略模式,相似predicate替換策略

2,模板方法,

3,觀察者模式,註冊的時候寫上方法

4,責任鏈模式,在註冊的時候像觀察者模式差很少

5,傳統簡單工廠,用map和supplier

相關文章
相關標籤/搜索