日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > java >内容正文

java

JavaEE_day_25_Lambda、SteamAPI

發(fā)布時間:2023/12/20 java 40 豆豆
生活随笔 收集整理的這篇文章主要介紹了 JavaEE_day_25_Lambda、SteamAPI 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

目錄

  • lambd表達(dá)式
  • Supplier
  • Consumer
  • Function
  • Predicate
  • 方法引用簡寫
  • 構(gòu)造方法簡寫
  • 數(shù)組聲明簡寫
  • StreamAPI
  • 1.lambd表達(dá)式

    • lamada表達(dá)式函數(shù)必須保證所傳遞函數(shù)是只有一個抽象方法的接口類.
    • 相當(dāng)于匿名內(nèi)部類(一個一次性的單一抽象方法接口類)的升級版,在箭頭函數(shù)調(diào)用lamuda表達(dá)式時,必須與抽象方法一一對應(yīng),否則調(diào)用失敗報錯
    • 單句不想返回,則加{}不用加return,
    Integer [] arr = {1,5,4,2,8,3,4,9};List<Integer> list = Arrays.asList(arr);//匿名內(nèi)部類實現(xiàn)排序(降序)list.sort(new Comparator<Integer>(){@Overridepublic int compare(Integer o1, Integer o2) {return o2-o1;}});//lambda表達(dá)式實現(xiàn)排序(升序)list.sort((o1,o2)->o1-o2);for (Integer integer : list) {System.out.print(integer +" ");}
    • 函數(shù)式接口,給lambda表達(dá)式操作空間只留一個抽象方法,可以有其他實現(xiàn)的方法, (就是一個像函數(shù)的接口類)

    有參的函數(shù)式接口(附三種調(diào)用方式)
    無參的直接寫call(()->System.out.println(“l(fā)ambda表達(dá)式”));

    public class _02_FunInterface {public static void main(String[] args) {String str = "有參函數(shù)式接口調(diào)用";// 1 匿名內(nèi)部類call(new MyFunctionInter2(){@Overridepublic void printMessage(String str) {System.out.println(str);}}, str);// 2 lambdacall(s -> System.out.println(s), str);// 3 創(chuàng)建函數(shù)對象MyFunctionInter2 inter2 = s -> System.out.println(s);call(inter2, str);}// str為 printMessage方法的參數(shù)public static void call(MyFunctionInter2 func,String str) {// 調(diào)用func對象 的printMessage方法 并傳入 strfunc.printMessage(str);} } @FunctionalInterface interface MyFunctionInter2 {void printMessage(String str); }

    2.supplier

    • 泛型中可以規(guī)定任意類型
    • 表示供應(yīng)商,所以有返回值,可以獲取數(shù)據(jù)
    // 實現(xiàn)接口函數(shù)public static Integer getResult(Supplier<Integer> supplier) {return supplier.get();} // 匿名內(nèi)部類實現(xiàn)int i = getResult(new Supplier<Integer>() {@Overridepublic Integer get() {return 2;}});System.out.println(i);// lambda表達(dá)式實現(xiàn)i = getResult(() -> 7);System.out.println(i);

    3.Consumer

    • 表示消費者接口,所以不需要返回值
    //前一個參數(shù)即為accept的實現(xiàn)方法體,后一個參數(shù)是傳入是accept要傳入的參數(shù)call((s)->System.err.println(s),str);}public static void call(Consumer<String> c,String msg){c.accept(msg);}

    4.Function

    • Function<T,R> 實現(xiàn)方法中傳入T類型,返回R類型
      R apply(T t) 方法
    public static void main(String[] args) {//寫的是apply的參數(shù)和返回值int num = convertType(x->(int)x, 'a');System.out.println(num);}// 把字符串轉(zhuǎn)換為數(shù)字public static Integer convertType(Function<Character,Integer> function, Character ch) {int i = function.apply(ch);return i;}

    5.Predicate

    • Predicate 接口 斷言接口,就是做一些判斷

    • booean test(T) 用于做校驗比較操作

    public static void main(String[] args) {String message = "ok1";boolean result = call(msg->msg.equals("ok"),message);System.out.println(result);}//booean test(T) 用于做校驗比較操作public static boolean call(Predicate<String> predicate, String message) {return predicate.test(message);}

    6.方法引用簡寫

    • Lambda表達(dá)式的另一種表示形式,提高復(fù)用率和靈活性

    • 當(dāng)要傳遞給Lambda體的操作,已經(jīng)有實現(xiàn)的方法了,可以使用方法引用!

    • 方法引用可以看做是Lambda表達(dá)式深層次的表達(dá)。換句話說,方法引用就是Lambda表達(dá)式,也就是函數(shù)式接口的一個實例,通過方法的名字來指向一個方法,可以認(rèn)為是Lambda表達(dá)式的一個語法糖。

    • 要求:實現(xiàn)接口的抽象方法的參數(shù)列表和返回值類型,必須與方法引用的方法的參數(shù)列表和返回值類型保持一致!

    • 格式:使用操作符“::” 將類(或?qū)ο? 與方法名分隔開來。

    • 如下三種主要使用情況:
      ?對象::實例方法名
      ?類::靜態(tài)方法名
      ?類::實例方法名

    對象::實例方法名

    public static void main(String[] args) {Integer i = new Integer(123);//lambda表達(dá)式Supplier<Integer> supplier = ()->i.hashCode();System.out.println(supplier.get());//對象的引用::實例方法Supplier<Integer> supplier1 = i::hashCode;System.out.println(supplier1.get());call(()->i.hashCode());call(i::hashCode);}public static Integer call(Supplier<Integer> sup){return sup.get();}

    類::靜態(tài)方法名

    int i = 123;//lambda表達(dá)式寫法Function<Integer,String> fun = x -> Integer.toBinaryString(i);System.out.println(fun.apply(i));//類名::靜態(tài)方法名()省略了參數(shù),因為調(diào)用apply時還會調(diào)用Function<Integer,String> fun1 = Integer::toBinaryString;System.out.println(fun1.apply(i));

    類::實例方法名

    //lambda表達(dá)式BiPredicate<String,String> bi = (x,y)->x.equals(y);System.out.println(bi.test("oak","ok"));//類名::實例方法BiPredicate<String,String> bi1 = String::equals;System.out.println(bi1.test("ock","ock"));

    7.構(gòu)造方法簡寫

    構(gòu)造方法

    //無參構(gòu)造器Supplier<Student> sup11 = () -> new Student();System.out.println(sup11.get());Supplier<Student> sup12 = Student::new;System.out.println(sup12.get());//有參構(gòu)造器Supplier<Student> sup21 = () -> new Student("王老菊");System.out.println(sup21.get().getName());//apply()的<參數(shù),返回值>Function<String,Student> sup22 = Student::new;System.out.println(sup22.apply("王老菊").getName());

    8.數(shù)組聲明簡寫

    數(shù)組聲明簡寫

    // 數(shù)組引用寫法,只能動態(tài)聲明,不能靜態(tài)聲明Function<Integer, Integer[]> fun1 = Integer[]::new;Integer[] arr1 = fun1.apply(2);System.out.println(arr1.length);

    9.StreamAPI

    • 簡言之,Stream API 提供了一種高效且易于使用的處理數(shù)據(jù)的方式。
      就是用來處理集合、數(shù)組的API,集合講的是數(shù)據(jù),而流是計算
      注意:
      ①Stream 自己不會存儲元素。
      ②Stream 不會改變源對象。相反,他們會返回一個持有結(jié)果的新Stream。
      ③Stream 操作是延遲執(zhí)行的。這意味著他們會等到需要結(jié)果的時候才執(zhí)行。

    9.1 創(chuàng)建流

    // 1 通過數(shù)組 Stream.ofString[] strings = { "a", "b", "c", "d" };Stream<String> stream1 = Stream.of(strings);// 2 通過集合List<String> strings2 = Arrays.asList(strings);Stream<String> stream2 = strings2.stream();// 3 通過Stream.generate 方法來創(chuàng)建// 這是一個無限流,無限大,通過這種方式創(chuàng)建的流,在操作的時候,最好使用limit進(jìn)行最大數(shù)量限制// generate的參數(shù)是 Supplier 只有一個get方法,是無參有返回值的// get方法的返回值,作為整個集合中的數(shù)據(jù),下面這個等于都賦值為1Stream<Integer> generate = Stream.generate(() -> 1);// 可以通過limit限制最多元素個數(shù)generate.limit(5).forEach(x -> System.out.println(x));// 4 通過Stream.iterate 方法來創(chuàng)建// 這是一個無限流,無限大,通過這種方式創(chuàng)建的流,在操作的時候,最好使用limit進(jìn)行最大數(shù)量限制// 第一個參數(shù)是起始值,第二個參數(shù)是UnaryOperator 繼承了Function 所以 有參有返回值// 1 就是起始值, x+2 就是步長,類似于一個死循環(huán),起始值是1,步長 是2,終止條件是trueStream<Integer> iterate = Stream.iterate(1, x->x+2);iterate.limit(5).forEach(x->System.out.println(x));// 5 已有類的Stream源生成APIString str = "abc";IntStream chars = str.chars();chars.forEach(x->System.out.println(x));

    9.2 流的中間操作(轉(zhuǎn)換算子)

    stream.(轉(zhuǎn)換算子).(動作算子)

    • filter : 對元素進(jìn)行過濾,不符合條件的,就不要了
    • distinct : 去掉重復(fù)
    • skip : 跳過多少個元素
    • limit : 取一個集合中的前幾條數(shù)據(jù)
    • map : 可以理解為是在遍歷集合的過程中,對元素進(jìn)行操作. 比如進(jìn)行判斷,集合元素是否大于4 ,返回值為boolean類型,或者對集合元素進(jìn)行更改,比如每個元素都自身+1
    • flatMap : 解決一個字符串?dāng)?shù)組,返回單一的字符串使用flatMap
    public static void main(String[] args) {String[] arr = { "a", "b", "c", "a" };List<String> strings = Arrays.asList(arr);// 創(chuàng)建流對象Stream<String> stream = strings.stream();// filter:對元素進(jìn)行過濾(參數(shù)為predicate(參數(shù)<T>返回值boolean))List<String> value = stream.filter(x -> x.equals("a")).collect(Collectors.toList());System.out.println(value);// 需要重新生成一個stream,否則報錯,不能使用同一個streamstream = strings.stream();value = stream.skip(1).collect(Collectors.toList());System.out.println(value);// map,在遍歷過程中,對元素進(jìn)行操作,返回Boolean類型stream = strings.stream();//在元素尾部添加字符串List value1 = stream.map(x -> x+"xxx").collect(Collectors.toList());System.out.println(value1);//distinct去重stream = strings.stream();value = stream.distinct().collect(Collectors.toList());System.out.println(value);//limit(n) :取集合中前n條數(shù)據(jù)stream = strings.stream();value = stream.limit(2).collect(Collectors.toList());System.out.println(value);//flatMap : 合并兩段數(shù)組String[] arr1 = {"abc","abc"};strings = Arrays.asList(arr1);stream = strings.stream();value = stream.map(x->x.split("")).flatMap(array->Arrays.stream(array)).collect(Collectors.toList());System.out.println(value);}

    9.3 流的終止操作(動作算子)

    stream.(轉(zhuǎn)換算子).(動作算子)

    • forEach : 循環(huán)
    • 計算 : min,max,count,average
    • 匹配 :anyMatch,allMatch,noneMatch,findFirst,findAny
    • 匯聚 : reduce
    • 收集器 : collect
    String[] arr = { "a", "b", "c" };List<String> strings = Arrays.asList(arr);Stream<String> stream = strings.stream();// 測試forEachstream.filter(x -> x.equals("a")).forEach(x -> System.out.println(x));// 測試 countstream = strings.stream();long count = stream.count();System.out.println(count);//統(tǒng)計 有幾個astream = strings.stream();count = stream.filter(x -> x.equals("a")).count();System.out.println(count);// collect收集器// 把結(jié)果收集,并組織成集合stream = strings.stream();List<String> list = stream.map(x -> x + "==").collect(Collectors.toList());System.out.println(list);

    總結(jié)

    以上是生活随笔為你收集整理的JavaEE_day_25_Lambda、SteamAPI的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。