JAVA自學筆記(10)—Stream流、方法引用

来源:https://www.cnblogs.com/mzq-/archive/2020/07/03/13226120.html
-Advertisement-
Play Games

開胃菜 ——實現遍歷集合,開啟Stream流的便利化 import java.util.ArrayList; import java.util.Collections; public class Main{ public static void main(String[] args) { Array ...


開胃菜

——實現遍歷集合,開啟Stream流的便利化

 

import java.util.ArrayList;
import java.util.Collections;


public class Main{
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<String>();
        ArrayList<String> list1 = new ArrayList<String>();
        Collections.addAll(list,"ab","cea","fshwe","dea");
        list.stream().
                filter(str -> str.contains("a")).
                filter(str -> str.length() == 3).
                forEach(str-> System.out.println(str));

    }
}

 

列印結果:

cea
dea

走進Stream流的世界

1.0 獲取stream流的方法

 

 

import java.util.*;
import java.util.stream.Stream;

public class Main{
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        list.stream();//第一種方式

        //特別的Map集合也可以間接的獲取
        Map<String,Integer> map=new HashMap<>();
        Set<String> keySet = map.keySet();
        keySet.stream();
        Collection<Integer> integers = map.values();
        integers.stream();

        Set<Map.Entry<String, Integer>> entries = map.entrySet();

        entries.stream();


        //第二種方式
        Stream<Integer> integerStream = Stream.of(1, 2, 3, 4, 5);//數組

    }
}

2.0 Stream流的方法

(1)forEach

 

import java.util.stream.Stream;

public class Main{
    public static void main(String[] args) {
        Stream<String> stream = Stream.of("a", "b", "c", "d", "e");
        stream.forEach((str)-> System.out.print(str+" "));
        //a b c d e 
    }
}

 

(2) filter()

import java.util.stream.Stream;

public class Main{
    public static void main(String[] args) {
        Stream<String> stream = Stream.of("baby", "boy", "home", "dream", "eage");
        Stream<String> a = stream.filter(str -> str.contains("a")).filter(str -> str.length() >=3);
        a.forEach((str)-> System.out.print(str+" "));
        //baby dream eage
    }
}

(3)Stream流的特點

 

(4)Map方法

import java.util.stream.Stream;

public class Main{
    public static void main(String[] args) {
        Stream<String> stream = Stream.of("12", "34", "56");
        stream.map((str)->Integer.parseInt(str)+1).
                forEach((Str)-> System.out.print(Str+" "));

        //13 35 57 
    }
}

(5)count方法

(6)limit方法

 

(7)skip方法

 

(8)concat方法

 

方法引用

—— 簡便你我他

1.0 通過對象名引用成員方法

 

public class Main{
    public static void PrintString(MessageBuilder mes)
    {
        mes.bulidString("hello");
    }
    public static void main(String[] args) {
        //Lambda
        PrintString((s)->{
            Printer pri=new Printer();
            pri.PrintUpper(s);//HELLO
        });

        //方法引用
        Printer printer=new Printer();
        PrintString(printer::PrintUpper);//HELLO
    }
}

2.0 通過類名引用靜態方法  

 

public class Main{
    public static int calmathod(int num,MessageBuilder mes)
    {
        return mes.Cal(num);
    }
    public static void main(String[] args) {
        int num=-10;
        /*
        int calmathod = calmathod(num, (number) -> {
            return Math.abs(number);
        });*/
        int calmathod=calmathod(num,Math::abs);
        System.out.println(calmathod);//10
    }
}

3.0 通過super引用父類的方法

public class Main extends FU{
    @Override
    public void show(){
        System.out.println("Hello,My soulmate!");
    }
    public void method(MessageBuilder mes){
        mes.greet();
    }
    public void Print()//調用父類方法
    {
        /*
        method(()->{
            FU fu = new FU();
            fu.show();
        });
        */
       method(super::show);//Hello,My friend!
    }
    public static void main(String[] args) {
     new Main().Print();
    }
}

4.0 通過this調用本類中的成員方法  

public class Main{
    public void method()
    {
        System.out.println("Hello world!");
    }
    public void showMethod(MessageBuilder mes){//函數式介面
        mes.show();
    }
    public void MethodPrint()
    {
        /*
        showMethod(()->{
            this.method();
        });
         */
        showMethod(this::method);
    }

    public static void main(String[] args) {
        new Main().MethodPrint();//Hello world!
    }
}

5.0 類的構造器(構造方法)  

public class Person {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Person() {
    }

    public Person(String name) {
        this.name = name;
    }
}

  

@FunctionalInterface
public  interface MessageBuilder {
    public abstract Person show(String name);
}

  

public class Main{
    public static String Method(String name,MessageBuilder mes)
    {
        Person person = mes.show(name);
        return person.getName();
    }
    public static void main(String[] args) {
        String name="布丁";
        /*
        String method = Method(name,(str)->{
             return new Person(str);
        });
         */

        String method = Method(name, Person::new);

        System.out.println(method);

    }
}

6.0 數組的構造器引用

@FunctionalInterface
public  interface MessageBuilder {
    public abstract int[] Builder(int length);
}

  

public class Main{
    public static int[] Method(int length,MessageBuilder mes)
    {
        int[] builder = mes.Builder(length);
        return builder;
    }
    public static void main(String[] args) {
        /*
        int[] method = Method(3, (length) -> {
            return new int[length];
        });
         */
        int[] method = Method(3, int[]::new);

        System.out.println(method.length);
    }
}

  


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 前言 剛回到家,又被公司群里的消息轟炸了。讓統計每個人最近是否去過石景山萬達廣場。 這基本上已經是每日必備了,只要有任何風吹草動,就需要我們填各種信息。 我們都知道,北京最近的疫情很不樂觀,從每天的數據就能看出來了。 也許很多小伙伴不在北京,是切實感受不到的。 就拿我自己舉例吧,在去公司的每一天,我 ...
  • 這篇博客還是整理從https://github.com/LyricTian/gin-admin 這個項目中學習的golang相關知識 作者在項目中使用了https://github.com/google/wire 做依賴註入,這個庫我之前沒有使用過,看了作者代碼中的使用,至少剛開始是看著優點懵,不知 ...
  • 轉載:https://blog.csdn.net/walkerJong/article/details/7946109 ...
  • # Definition for a binary tree node.class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = Nonea = TreeNode(1)b = TreeNode( ...
  • 編寫程式,讀取在1到100 之間的整數,然後計算每個數出現的次數。假定輸入是以0 結束的。 下麵是這個程式的一個運行示例: Write a program that reads the integers between 1and 100 and counts the occurrences of e ...
  • 安裝pandas 通過python pip安裝pandas pip install pandas pandas數據結構 pandas常用數據結構包括:Series和DataFrame Series Series是一種一維的數組型對象,包含一個值序列(與numpy中的數據類型相似),數據標簽(稱為索引 ...
  • pygame 圖像 / 圖形繪製 1. pygame 的圖像繪製 pygame 支持多種存儲圖像的方式(也就是圖片格式),例如 JPEG、PNG 等,具體支持 JPEG (一般擴展名為 .jpg 或者 .jpeg ,數位相機、網上的圖片基本上都是這種格式,這是一種有損壓縮方式,儘管對圖片的質量有所損 ...
  • opencv——threshold閾值處理、自適應閾值處理、otsu處理(大津法) ...
一周排行
    -Advertisement-
    Play Games
  • GoF之工廠模式 @目錄GoF之工廠模式每博一文案1. 簡單說明“23種設計模式”1.2 介紹工廠模式的三種形態1.3 簡單工廠模式(靜態工廠模式)1.3.1 簡單工廠模式的優缺點:1.4 工廠方法模式1.4.1 工廠方法模式的優缺點:1.5 抽象工廠模式1.6 抽象工廠模式的優缺點:2. 總結:3 ...
  • 新改進提供的Taurus Rpc 功能,可以簡化微服務間的調用,同時可以不用再手動輸出模塊名稱,或調用路徑,包括負載均衡,這一切,由框架實現並提供了。新的Taurus Rpc 功能,將使得服務間的調用,更加輕鬆、簡約、高效。 ...
  • 本章將和大家分享ES的數據同步方案和ES集群相關知識。廢話不多說,下麵我們直接進入主題。 一、ES數據同步 1、數據同步問題 Elasticsearch中的酒店數據來自於mysql資料庫,因此mysql數據發生改變時,Elasticsearch也必須跟著改變,這個就是Elasticsearch與my ...
  • 引言 在我們之前的文章中介紹過使用Bogus生成模擬測試數據,今天來講解一下功能更加強大自動生成測試數據的工具的庫"AutoFixture"。 什麼是AutoFixture? AutoFixture 是一個針對 .NET 的開源庫,旨在最大程度地減少單元測試中的“安排(Arrange)”階段,以提高 ...
  • 經過前面幾個部分學習,相信學過的同學已經能夠掌握 .NET Emit 這種中間語言,並能使得它來編寫一些應用,以提高程式的性能。隨著 IL 指令篇的結束,本系列也已經接近尾聲,在這接近結束的最後,會提供幾個可供直接使用的示例,以供大伙分析或使用在項目中。 ...
  • 當從不同來源導入Excel數據時,可能存在重覆的記錄。為了確保數據的準確性,通常需要刪除這些重覆的行。手動查找並刪除可能會非常耗費時間,而通過編程腳本則可以實現在短時間內處理大量數據。本文將提供一個使用C# 快速查找並刪除Excel重覆項的免費解決方案。 以下是實現步驟: 1. 首先安裝免費.NET ...
  • C++ 異常處理 C++ 異常處理機制允許程式在運行時處理錯誤或意外情況。它提供了捕獲和處理錯誤的一種結構化方式,使程式更加健壯和可靠。 異常處理的基本概念: 異常: 程式在運行時發生的錯誤或意外情況。 拋出異常: 使用 throw 關鍵字將異常傳遞給調用堆棧。 捕獲異常: 使用 try-catch ...
  • 優秀且經驗豐富的Java開發人員的特征之一是對API的廣泛瞭解,包括JDK和第三方庫。 我花了很多時間來學習API,尤其是在閱讀了Effective Java 3rd Edition之後 ,Joshua Bloch建議在Java 3rd Edition中使用現有的API進行開發,而不是為常見的東西編 ...
  • 框架 · 使用laravel框架,原因:tp的框架路由和orm沒有laravel好用 · 使用強制路由,方便介面多時,分多版本,分文件夾等操作 介面 · 介面開發註意欄位類型,欄位是int,查詢成功失敗都要返回int(對接java等強類型語言方便) · 查詢介面用GET、其他用POST 代碼 · 所 ...
  • 正文 下午找企業的人去鎮上做貸後。 車上聽同事跟那個司機對罵,火星子都快出來了。司機跟那同事更熟一些,連我在內一共就三個人,同事那一手指桑罵槐給我都聽愣了。司機也是老社會人了,馬上聽出來了,為那個無辜的企業經辦人辯護,實際上是為自己辯護。 “這個事情你不能怪企業。”“但他們總不能讓銀行的人全權負責, ...