Lambda表達(dá)式(三)

Stream API

A squence ofelement supporting sequential and parallel affregate oprations Stream 是一組用來操作數(shù)組、集合的API

Stream 的特點(diǎn)

  1. 不是數(shù)據(jù)結(jié)構(gòu),沒有內(nèi)部存儲(chǔ)
  2. 不支持索引訪問
  3. 延遲計(jì)算
  4. 支持并行
  5. 很容易生成數(shù)組或者集合(List,Set)
  6. 支持過濾,查找,轉(zhuǎn)換,匯總等操作

Stream 運(yùn)行機(jī)制

  • Stream分為 源source,中間操作,終止操作

  • 流的源可以是一個(gè)數(shù)組一個(gè)集合、一個(gè)生成器方法、一個(gè)I/O通道等等

  • 一個(gè)流可以有零個(gè)或者多個(gè)中間操作,每一個(gè)中間操作都會(huì)返回一個(gè)新的流,供下一個(gè)操作使用。一個(gè) 流只可以使用一次,一個(gè)流只會(huì)有一個(gè)終止操作

  • Stream只有遇到終止操作,它的源才開始執(zhí)行遍歷操作

Stream常用API

流的創(chuàng)建

  1. 通過數(shù)組
  2. 通過集合
  3. 通過Stream.generate方法來創(chuàng)建
  4. 通過Stream.iterate方法來創(chuàng)建
  5. 其他API(比如文件,字符串)

中間操作

  1. 過濾 filter
  2. 去重 distinct
  3. 排序 sorted
  4. 截取 limit、skip
  5. 轉(zhuǎn)換 map/flatMap
  6. 其他 peek

終止操作

  1. 循環(huán) forEach
  2. 計(jì)算 min、max、count
  3. 匹配 anyMatch、allMatch、noneMatch、findFirst、findAny
  4. 匯聚 reduce
  5. 收集器 toArray collect

流的創(chuàng)建

package lambda2;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.stream.IntStream;
import java.util.stream.Stream;

/**
 * 流的創(chuàng)建
 *
 */
public class CreateStream {
    /**
     * 通過數(shù)組
     */
    static void gen1() {
        Integer[] arr= {1,2,3,4};
       Stream<Integer> stream=Stream.of(arr);
       stream.forEach(System.out::println);
    }
    /**
     * 通過集合
     */
    static void gen2() {
        String[] arr= {"a","b","1","2","3"};
        List<String> list=Arrays.asList(arr) ;
       Stream<String> stream=list.stream();
       stream.forEach(System.out::println);
    }
    /**
     * 通過Stream.generate方法來創(chuàng)建
     */
    static void gen3() {
        Stream<String> stream=Stream.generate(()-> "a");//無止境的流,因?yàn)榱鳑]有終止
        //stream.limit(10);截取流,取前10個(gè)
        stream.limit(10).forEach(System.out::println);
    }
    /**
     * 通過Stream.iterate方法來創(chuàng)建
     */
    static void gen4() {
        Stream<Integer> stream=Stream.iterate(1, x->x+1);//無止境的流,因?yàn)榱鳑]有終止
        //stream.limit(10);截取流,取前10個(gè)
        stream.limit(10).forEach(System.out::println);
    }
    
    /**
     * 通過其他方式(字符串)
     */
    static void gen5() {
        String str="jarWorker";
        IntStream stream=str.chars();//轉(zhuǎn)換成intStream流
        //void forEach(IntConsumer action);相當(dāng)于conSumer:輸入
        stream.forEach(x->System.out.println(x));
        //stream.forEach(System.out::println);//方法的引用
    }
    /**
     * 通過其他方式(讀取文件)
     * @throws IOException 
     */
    static void gen6() throws IOException {
        
        String path="f:/InstanceMethod.java";
        File file=new File(path);
        if(file.exists()) {
            file.delete();
        }
        if(!file.exists()) {
            boolean flag=file.createNewFile();
            if(flag) {
                FileOutputStream out=new FileOutputStream(file,true); 
                String content="package lambda1;\r\n" + 
                        "import java.util.function.Supplier;\r\n" + 
                        "/**\r\n" + 
                        " * 實(shí)例方法引用\r\n" + 
                        " * 如果函數(shù)式接口恰巧可以通過調(diào)用一個(gè)實(shí)例的實(shí)例方法來實(shí)現(xiàn),就可以使用調(diào)動(dòng)實(shí)例方法來引用\r\n" + 
                        " */\r\n" + 
                        "public class InstanceMethod {\r\n" + 
                        "   /**\r\n" + 
                        "    * 實(shí)例方法\r\n" + 
                        "    * \r\n" + 
                        "    * @return\r\n" + 
                        "    */\r\n" + 
                        "   private String insert() {\r\n" + 
                        "       return \"hello lambda\";\r\n" + 
                        "   }\r\n" + 
                        "   \r\n" + 
                        "public static void main(String[] args) {\r\n" + 
                        "   Supplier<String> s = () -> {\r\n" + 
                        "       return new InstanceMethod().insert();\r\n" + 
                        "   };\r\n" + 
                        "   System.out.println(\"lambda表達(dá)式:\" + s.get());\r\n" + 
                        "   // 方法的引用\r\n" + 
                        "   Supplier<String> s1 = new InstanceMethod()::insert;\r\n" + 
                        "   System.out.println(\"方法的引用:\" + s1.get());\r\n" + 
                        " \r\n" + 
                        "}\r\n" + 
                        "}";
                //這里設(shè)置為了utf-8
                out.write(content.getBytes("utf-8"));
                
                } 
            }
        
        //這里可能會(huì)涉及編碼的問題,盡量讓文件的編碼格式為utf-8
        Stream<String> stream= Files.lines(Paths.get(path));
        stream.forEach(System.out::println);
    }
    public static void main(String[] args) throws IOException{
        gen1();
        gen2();
        gen3();
        gen4();
        gen5();
        gen6();
    }
}


中間操作

package lambda2;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.function.Supplier;
import java.util.stream.Stream;

/**
 * 
 * 中間操作
 *
 */
public class Middle {
    /**
     * 過濾:filter
     */
    static void filterMiddle() {

        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6);
        Stream<Integer> stream = list.stream();
        stream.filter((x) -> {
            System.out.println("進(jìn)入此方法");
            return x % 2 == 1;
        }).forEach(System.out::println);// 代碼沒有執(zhí)行forEach前并不會(huì)打印出任何東西,包括“進(jìn)入此方法”,因?yàn)椴]有終止流
        //stream.forEach(System.out::println);因?yàn)橐粋€(gè) Stream 只可以使用一次
    }
    
    /**
     * 去重:distinct
     */
    static void distinctMiddle() {

        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 5);
        list.stream().distinct().forEach(System.out::println);
    }
    
    /**
     * 排序:sort
     */
    static void sortedMiddle() {

        List<Integer> list = Arrays.asList(1, 2, 6, 4, 5, 5,3);
        //以下做了去重和排序兩個(gè)中間操作,說明說一個(gè)Stream的中間操作可以是多個(gè)
        list.stream().distinct().sorted().forEach(System.out::println);//正序
        
        list.stream().distinct().sorted(Comparator.reverseOrder()).forEach(System.out::println);//倒序
    }
    
    /**
     * 截取: limit、skip
     */
    static void InterceptionMiddle() {

        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6);
        
         //跳過1,2
        list.stream().skip(2).forEach(System.out::println);

         //截取 1, 2
        list.stream().limit(2).forEach(System.out::println);
        
        list.stream().limit(2).skip(2).forEach(System.out::println);
    }
    /**
     * 轉(zhuǎn)換: map/flatMap
     */
    static void conversionMiddle() {

        List<String> list = Arrays.asList("1","2","3");
        
        
        list.stream().map(x->x).forEach(System.out::println);//還是字符串
        //轉(zhuǎn)換成int類型
        list.stream().mapToInt(x->Integer.valueOf(x)).forEach(System.out::println);//已經(jīng)是int類型
        
        Supplier<List<List<String>>> s=ArrayList::new;
        List<List<String>> list1=s.get();
        List<String> l1 = Arrays.asList("1","3");
        List<String> l2 = Arrays.asList("2","4");
        list1.add(l1);
        list1.add(l2);
        
        //flatMap 大致上的意思就是有很多層的嵌套
        list1.stream().flatMap((x)->x.stream()).forEach(System.out::println);//還是字符串
        
        list1.stream().flatMapToInt((x)->x.stream().mapToInt(v->Integer.valueOf(v))).forEach(System.out::println);//已經(jīng)是int類型
        
    }
    /**
     * 其他: peek
     */
    static void otherMiddle() {
        //peek和map的區(qū)別
        //peek接收一個(gè)沒有返回值的λ表達(dá)式,可以做一些輸出,外部處理等。map接收一個(gè)有返回值的λ表達(dá)式,之后Stream的泛型類型將轉(zhuǎn)換為map參數(shù)λ表達(dá)式返回的類型
        
        Supplier<List<List<String>>> s=ArrayList::new;
        List<List<String>> list1=s.get();
        List<String> l1 = Arrays.asList("1","3");
        List<String> l2 = Arrays.asList("2","4");
        list1.add(l1);
        list1.add(l2);
        
        //下面的兩個(gè)結(jié)果是一樣的,只遍歷了list1后沒有繼續(xù)往下遍歷
        //peek方法接收一個(gè)Consumer的入?yún)?沒有返回值,而map方法的入?yún)?Function,有返回值
        list1.stream().peek((x)->x.stream()).forEach(System.out::println);
        
        list1.stream().peek((x)->x.stream().mapToInt(Integer::valueOf)).forEach(System.out::println);
        
    }
    
public static void main(String[] args) {
    filterMiddle();
    distinctMiddle();
    sortedMiddle();
    InterceptionMiddle() ;
    conversionMiddle();
    otherMiddle() ;
    
}

}

終止操作

package lambda2;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 
 * 終止操作
 *
 */
public class Termination {
    static List<Integer>  number=Arrays.asList(1,2,3,4,5,6,7);
    
    /**
     * 循環(huán)
     * foreach
     */
    static void termination1() {
        Stream<Integer> stream = number.stream();
        stream.forEach(System.out::println);
    }
    
    /**
     * 計(jì)算
     * min
     */
    static void termination2() {
        Stream<Integer> stream = number.stream();
        int min=stream.min((a,b)->a-b).get();
        System.out.println(min);
    }
    /**
     * 計(jì)算
     * max
     */
    static void termination3() {
        Stream<Integer> stream = number.stream();
        int max=stream.max((a,b)->a-b).get();
        System.out.println(max);
    }
    
    /**
     * 計(jì)算
     * count
     */
    static void termination4() {
        Stream<Integer> stream = number.stream();
        long count= stream.count();
        System.out.println(count);
    }
    
    /**
     * 匹配
     * anyMatch
     */
    static void termination5() {
        Stream<Integer> stream = number.stream();
        boolean flag =stream.anyMatch(x->x.equals(10));
        System.out.println(flag);
    }
    
    /**
     * 匹配
     * allMatch
     */
    static void termination6() {
        Stream<Integer> stream = number.stream();
        boolean flag =stream.allMatch(x->x==1||x==2||x==3||x==4||x==5||x==6||x==7);
            
        
        System.out.println(flag);
    }
    /**
     * 匹配
     * noneMatch
     */
    static void termination7() {
        Stream<Integer> stream = number.stream();
        boolean flag =stream.noneMatch(x->x==10);
            
        System.out.println(flag);
    }
    
    /**
     * 匹配
     * findFirst
     */
    static void termination8() {
        Stream<Integer> stream = number.stream();
        int first =stream.sorted(Comparator.reverseOrder()).parallel().findFirst().orElse(5);
            
        System.out.println(first);
    }
    /**
     * 匹配
     * findAny
     * 
     * findAny并不是隨機(jī)地選一個(gè),如果是數(shù)據(jù)較少,串行地情況下,一般會(huì)返回第一個(gè)結(jié)果,如果是并行的情況,那就不能確保是第一個(gè)
     */
    static void termination9() {
        Stream<Integer> stream = number.stream();
        Optional<Integer> op =stream.sorted(Comparator.reverseOrder()).parallel().findAny();
        Integer any=op.get();
        System.out.println(any);
    }
    /**
     * 收集器
     * toArray collect
     * 
     */
    static void termination10() {
        List<Integer> list1=Stream.iterate(1, x->x+1).limit(50).collect(Collectors.toList());
        
        Object[] array=Stream.iterate(1, x->x+1).limit(50).toArray();
    
    }
    /**
     * 匯聚
     * reduce
     * 
     */
    static void termination11() {
        Stream<Integer> stream = number.stream();
        int result=stream.reduce((a,b)->a+b).get();
        System.out.println(result);
    }

    public static void main(String[] args) {
        termination1();
        termination2();
        termination3();
        termination4();
        termination5();
        termination6();
        termination7();
        termination8();
        termination9();
        termination10();
        termination11();

    }
}

并行流和串行流的轉(zhuǎn)換

package lambda2;

import java.util.stream.Stream;

/**
 * 并行流和串行流的轉(zhuǎn)換
 * 
 * 串行變并行 parallel()
 * 并行變串行 sequential()
 */
public class ParallelStream {
public static void main(String[] args) {
    
    
    String str="12,32,21";
    //串行變并行 parallel()
    int max1=Stream.of(str.split(",")).parallel().peek(x->{
        System.out.println(Thread.currentThread().getName());
        
    }).mapToInt(Integer::valueOf).max().getAsInt();
     
    //并行變串行 sequential()
    int max2=Stream.of(str.split(",")).parallel().mapToInt(Integer::valueOf).peek(x->{
        System.out.println(Thread.currentThread().getName());
        
    }).sequential().max().getAsInt();
    System.out.println(max1);
    System.out.println(max2);
}
}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容