jdk 8,stream(groupBy ,reduce ,optional, sorted的用法)


1, 函數式編程

lambda 是一個接口的方法,省略了接口的書寫,函數式接口就是只定義一個抽象方法的接口runable就是一個函數式接口

public static void process(Runnable r){
        r.run();
    }
public static void main(String args[]){
     Runnable r1 = () -> System.out.println("Hello World 1");
     Runnable r2 = new Runnable(){
      
     public void run(){
           System.out.println("Hello World 2");
         }
     };
     process(r1);
     process(r2);
     process(() -> System.out.println("Hello World 3"));
 }

java.util.function.Predicate<T>接口定義了一個名 test的抽象方法,它接受一份 T類型的對象,並返回一個boolean

2, stream調用了toMap()方法,可能生成map的key有重復的情況

 將java數組轉化為stream流時,如果stream調用了toMap()方法,可能生成map的key有重復的情況。

//如果key值有重復,那么方法會拋異常(duplic.. key excption)
Stream.of(emps).collect(Collectors.toMap(Emp::getId, Emp::getName);
//改寫成以下方式,針對重復key的  覆蓋之前的value
Stream.of(emps).collect(Collectors.toMap(Emp::getId, Emp::getName,(k,v)->v));

3, stream流處理

1, java 8中的流處理debug方法

 List<Integer> numbers = new ArrayList<Integer>();
 numbers.add(1);numbers.add(2);numbers.add(3);numbers.add(4);
 List<Integer> result = numbers.stream()
         .peek(x -> System.out.println("from stream: " + x))
         .map(x -> x + 17)
         .peek(x -> System.out.println("after map: " + x))
         .filter(x -> x % 2 == 0)
         .peek(x -> System.out.println("after filter: " + x))
         .limit(3)
         .peek(x -> System.out.println("after limit: " + x))
         .collect(toList());
//output
from stream: 1
after map: 18
after filter: 18
after limit: 18
from stream: 2
after map: 19
from stream: 3
after map: 20
after filter: 20
after limit: 20
from stream: 4
after map: 21

使用peek查看Stream流水線中的數據流的值 通過peek操作我們能清楚地了解流水線操作中每一步的輸出結果,可以用來debug。

從結果中可以看到stream的map,filter ,limit 方法都是延遲加載的,調用這些方法時只是先做個記錄,程序直到執行到collect的方法時,才會正式對stream流進行所有方法操作。所以”from stream“這個語句是隔開執行(隔開打印的)。

 

2,groupBy的用法

//將saleList按照相同時間,平台,種類進行分組,結果是相同時間,相同平台,相同種類的sale對象會放在同一個List里。返回的map的keys是‘s.getStDate() + '_'....’這一串
,values是一個list。
Map<String,List<Sales>> trendMap = salesList.stream().collect(Collectors.groupingBy(
                s -> s.getStDate() + "_" + s.getPlatform() + "_" + s.getCategoryId()));

  

3,reduce的用法,將a對象和b對象進行相加的操作

Optional<Sales> optional = childList.stream().reduce((a,b) -> {
                a.setRealPrice(a.getRealPrice().add(b.getRealPrice()));
                a.setSaleAmount(a.getSaleAmount() + b.getSaleAmount());
                return a;
            });
//如果optional不為null,那么調用saleListTotal.add()的方法
optional.ifPresent(salesListTotal::add);

/**
 * If a value is present, invoke the specified consumer with the value,
 * otherwise do nothing.
 *
 * @param consumer block to be executed if a value is present
 * @throws NullPointerException if value is present and {@code consumer} is
 * null
 */
public void ifPresent(Consumer<? super T> consumer) {
    if (value != null)
        consumer.accept(value);
}

 

4,sorted方法的用法

salesListTotal=salesListTotal.stream().sorted(Comparator.comparing(Sales::getCategoryId)).collect(Collectors.toList());

  



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM