1. 程式人生 > >Java8的Stream API使用

Java8的Stream API使用

案例一:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;

import org.junit.Test;

/**
 * @author xyphf
 * @date 2018年8月23日
 * 
 * 一、Stream 的三個操作步驟
 * 
 * 1、建立Stream
 * 
 * 2、中間操作
 * 
 * 3、終止操作(終端操作)
 */
public class TestStreamAPI1 {
	
	// 建立 Stream
	@Test
	public void test1() {
		//1. 可以通過Collection 系列集合提供的 stream() 獲取序列流  或 parallelStream()獲取並行流
		List<String> list = new ArrayList<>();
		// 第一種獲取流的方式
		Stream<String> stream1 = list.stream();
		
		//2. 通過Arrays 種的靜態方法stream() 獲取陣列流
		// 第二種獲取流的方式
		Employee[] emps = new Employee[10];
		Stream<Employee> stream2 = Arrays.stream(emps);
		
		//3. 通過Stream類中的靜態方法 of()方法
		// 第三中獲取流的方式
		Stream<String> stream3 = Stream.of("aa","bb","cc");
		
		//4. 建立無限流
		
		// 迭代
		// 第四種建立流的方式
		Stream<Integer> stream4 = Stream.iterate(0, (x) -> x + 2);
//		stream4.forEach(System.out::println);
		// 加一部中間操作,限制數量
		stream4.limit(10).forEach(System.out::println);
		
		// 生成
		Stream.generate(() -> Math.random())
		.limit(5)
		.forEach(System.out::println);
	}
}

案例二:

Stream的中間操作

多個中間操作可以連線起來形成一個流水線,除非流水線上觸發終止操作,否則中間操作不會執行任何處理!而在終止操作時一次性全部處理,稱為“惰性求值”。

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Stream;

import org.junit.Test;

/**
 * 一、Stream 的三個操作步驟
 * 
 * 1、建立Stream
 * 
 * 2、中間操作
 * 
 * 3、終止操作(終端操作)
 */
public class TestStreamAPI2 {
	
	List<Employee> emps = Arrays.asList(
			new Employee(101, "張三", 18, 9999.99),
			new Employee(102, "李四", 59, 5555.55),
			new Employee(103, "王五", 26, 3333.33),
			new Employee(104, "趙六", 36, 6666.66),
			new Employee(105, "田七", 12, 8888.88),
			new Employee(105, "田七", 12, 8888.88),
			new Employee(105, "田七", 12, 8888.88)
	);

	//中間操作
	
	/*
	 * 篩選與切片
	 * filter——接收 Lambda , 從流中排除某些元素。
	 * limit——截斷流,使其元素不超過給定數量。
	 * skip(n) —— 跳過元素,返回一個扔掉了前 n 個元素的流。若流中元素不足 n 個,則返回一個空流。與 limit(n) 互補
	 * distinct——篩選,通過流所生成元素的 hashCode() 和 equals() 去除重複元素
	 */
	

	// 內部迭代: 迭代操作由Stream API完成
	@Test
	public void test1() {
		// 中間操作:不會執行任何操作
//		Stream<Employee> stream = emps.stream()
//							.filter((e) -> e.getAge() > 35);
//		stream.forEach(System.out::println);
		
		Stream<Employee> stream = emps.stream()
								  .filter((e) -> {
									System.out.println("Stream API 的中間操作");
									return e.getAge() > 35;
								  });
		// 終止操作:一次性執行全部內容,即“惰性求值”
		stream.forEach(System.out::println);
	}
	
	// 外部迭代:我們自己寫的迭代
	@Test
	public void test2() {
		Iterator<Employee> it = emps.iterator();
		
		while(it.hasNext()){
			System.out.println(it.next());
		}
	}
	
	@Test
	public void test3() {
//		emps.stream()
//				.filter((e) -> e.getSalary() > 5000)
//				.limit(2)
//				.forEach(System.out::println);
		emps.stream()
		.filter((e) -> {
			System.out.println("短路!");
			return e.getSalary() > 5000;
		})
		.limit(2)
		.forEach(System.out::println);
	}
	
	@Test
	public void test4(){
//		emps.stream()
//		.filter((e)->e.getSalary() > 5000)
//		.skip(2)
//		.forEach(System.out::println);
		emps.stream()
			.filter((e)->e.getSalary() > 5000)
			.skip(2)
			.distinct() // 要想去重成功,emps實體類裡 必須重寫hashCode() 和 equals()
			.forEach(System.out::println);
	}

	//中間操作
	/*
	 * 對映
	 * map——接收 Lambda , 將元素轉換成其他形式或提取資訊。接收一個函式作為引數,該函式會被應用到每個元素上,並將其對映成一個新的元素。
	 * flatMap——接收一個函式作為引數,將流中的每個值都換成另一個流,然後把所有流連線成一個流
	 */
	
	@Test
	public void test5(){
		List<String> list = Arrays.asList("aaa", "bbb", "ccc", "ddd", "eee");
		
		list.stream()
			.map((str) -> str.toUpperCase())
			.forEach(System.out::println);
		
		System.out.println("-------------------------------");
		
		emps.stream()
			.map(Employee::getName)
			.forEach(System.out::println);
		
		System.out.println("-------------------------------");
		
//		Stream<Stream<Character>> stream = list.stream()
//			.map(TestStreamAPI2::filterCharacter);
//		
//		stream.forEach((sm) ->{
//			sm.forEach(System.out::println);
//		});
		
		System.out.println("-------------------------------");
		
		Stream<Character> sm = list.stream()
				.flatMap(TestStreamAPI2::filterCharacter);
		
		sm.forEach(System.out::println);
	}
	
	public static Stream<Character> filterCharacter(String str){
		List<Character> list = new ArrayList<>();
		for(Character ch : str.toCharArray()) {
			list.add(ch);
		}
		return list.stream();
	}
	
	public void test6(){
		List<String> list = Arrays.asList("aaa", "bbb", "ccc", "ddd", "eee");
		
		List list2 = new ArrayList();
		list2.add(11);
		list2.add(22);
		list2.addAll(list);
	}
	
	//中間操作
	/**
	 * 排序
	 * sorted()--自然排序(Comparable)
	 * sorted(Comparator com)--定製排序(Comparator)
	 */
	
	public void test7(){
		List<String> list = Arrays.asList("aaa", "bbb", "ccc", "ddd", "eee");
		
		list.stream()
			.sorted()
			.forEach(System.out::println);
		
		System.out.println("-------------------------------");
		
		emps.stream()
			.sorted((e1, e2) -> {
				if(e1.getAge().equals(e2.getAge())){
					return e1.getName().compareTo(e2.getName());
				} else {
					return -e1.getAge().compareTo(e2.getAge());
				}
			}).forEach(System.out::println);
	}
	
}

案例三:

import java.util.Arrays;
import java.util.DoubleSummaryStatistics;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

import org.junit.Test;

import com.atguigu.java8.Employee.Status;

/*
 * 終止操作 
 */
public class TestStreamAPI3 {
	
	List<Employee> employes = Arrays.asList(
			new Employee(102, "李四", 79, 6666.66, Status.BUSY),
			new Employee(101, "張三", 18, 9999.99, Status.FREE),
			new Employee(103, "王五", 28, 3333.33, Status.VOCATION),
			new Employee(104, "趙六", 8, 7777.77, Status.BUSY),
			new Employee(105, "田七", 38, 5555.55, Status.BUSY)
	);
	
	/*
	 * 查詢與匹配
	 * allMatch——檢查是否匹配所有元素
	 * anyMatch——檢查是否至少匹配一個元素
	 * noneMatch——檢查是否沒有匹配所有元素
	 * findFirst——返回第一個元素
	 * findAny——返回當前流中的任意元素
	 * count——返回流中元素的個數
	 * max——返回流中最大值
	 * min——返回流中最小值
	 */
	@Test
	public void test1(){
			// allMatch——檢查是否匹配所有元素
		 boolean b1 = employes.stream()
					.allMatch((e) -> e.getStatus().equals(Status.BUSY));
			System.out.println(b1);
			
			// anyMatch——檢查是否至少匹配一個元素
		 boolean b2 = employes.stream()
					.anyMatch((e) -> e.getStatus().equals(Status.BUSY));
		 	System.out.println(b2);
		 	
		 	// noneMatch——檢查是否沒有匹配所有元素
		 boolean b3 = employes.stream()
		 			.noneMatch((e) -> e.getStatus().equals(Status.BUSY));
		 	System.out.println(b3);
		 	
		 // 按工資正排序 並查詢第一個 工資最低的
		  Optional<Employee> op = employes.stream()
		 			.sorted((e1,e2) -> Double.compare(e1.getSalary(), e2.getSalary()))
		 			.findFirst();
		  // 如果op裡面的值是空的,那麼你就有一個替代的物件
		  // op.orElse(other);
		  System.out.println(op.get());
		  
			 // 按工資倒排序 並查詢第一個 工資最高的 在前面加一個-號
		  Optional<Employee> op1 = employes.stream()
		 			.sorted((e1,e2) -> -Double.compare(e1.getSalary(), e2.getSalary()))
		 			.findFirst();
		  // 如果op裡面的值是空的,那麼你就有一個替代的物件
		  // op.orElse(other);
		  System.out.println(op1.get());
		  
		  // findAny——返回當前流中的任意元素
		  Optional<Employee> op2 = employes.parallelStream()
		  		  .filter((e) -> e.getStatus().equals(Status.FREE))
		  		  .findAny();
		  System.out.println(op2.get());  
	}
	
	@Test
	public void test2(){
		// count——返回流中元素的個數
		Long count = employes.stream()
				.count();
		System.out.println(count); 
		
		// max——返回流中最大值
		Optional<Employee> op1 = employes.stream()
				.max((e1,e2) -> Double.compare(e1.getSalary(), e2.getSalary()));
		System.out.println(op1); 
		
		// 獲取最少工資是多少
		Optional<Double> op2 = employes.stream()
				.map(Employee::getSalary)
				.min(Double::compare);
		System.out.println(op2.get()); 
	}
	
	/*
	 * 規約
	 * reduce(T identity,BinaryOperator) / reduce(BinaryOperator) —— 可以將流中元素反覆結合起來,得到一個值。
	 */
	@Test
	public void test3(){
		List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
		Integer sum = list.stream()
			.reduce(0, (x,y) -> x + y);
		System.out.println(sum); 
		
		System.out.println("-------------------------------");
		
		// 計算當前公司的工資總和是多少
		Optional<Double> op = employes.stream()
				.map(Employee::getSalary)
				.reduce(Double::sum);
		System.out.println(op.get());
	}
	
	/*
	 * collect——將流轉換為其他形式。接收一個Collector介面的實現,用於給Stream中元素做彙總的方法
	 */
	@Test
	public void test4(){
		// 將所有的員工名字放入list
		List<String> list = employes.stream()
				.map(Employee::getName)
				.collect(Collectors.toList());
		list.forEach(System.out::println);
		
		System.out.println("-------------------------------");
		// 將所有的員工名字放入Set 去重
		Set<String> set = employes.stream()
						.map(Employee::getName)
						.collect(Collectors.toSet());
		set.forEach(System.out::println);
		
		System.out.println("-------------------------------");
		HashSet<String> hs = employes.stream()
				.map(Employee::getName)
				.collect(Collectors.toCollection(HashSet::new));
		hs.forEach(System.out::println);
	}
	
	@Test
	public void test5(){
		// 總數
		Long count = employes.stream()
				.collect(Collectors.counting());
		System.out.println(count);
		
		System.out.println("-------------------------------");
		// 平均值
		Double avg = employes.stream()
				.collect(Collectors.averagingDouble(Employee::getSalary));
		System.out.println(avg);
		
		//總和
		Double sum = employes.stream()
				.collect(Collectors.summingDouble(Employee::getSalary));	
		System.out.println(sum);
		
		System.out.println("-------------------------------");
		// 求最大值
		Optional<Double> max = employes.stream()
				.map(Employee::getSalary)
				.collect(Collectors.maxBy(Double::compare));
		System.out.println(max.get());
		
		System.out.println("-------------------------------");
		// 最小值
		Optional<Employee> op = employes.stream()
				.collect(Collectors.minBy((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary())));
		System.out.println(op.get());
	}
	
	// 分組
	@Test
	public void test6(){
		Map<Status, List<Employee>> map = employes.stream()
				.collect(Collectors.groupingBy(Employee::getStatus));
		System.out.println(map);
	}
	
	// 多級分組
	@Test
	public void test7(){
		Map<Status, Map<String, List<Employee>>> map = employes.stream()
				.collect(Collectors.groupingBy(Employee::getStatus, Collectors.groupingBy((e) -> {
					if(e.getAge() >= 60)
						return "老年";
					else if(e.getAge() >= 35)
						return "中年";
					else
						return "成年";
				})));
			
		System.out.println(map);
	}
	
	// 分割槽  滿足條件的一個區,不滿足條件的一個區
	@Test
	public void test8(){
		Map<Boolean, List<Employee>> map = employes.stream()
				.collect(Collectors.partitioningBy((e) -> e.getSalary() >= 5000));
		System.out.println(map);
	}
	
	// 組函式的另一種獲取方式
	@Test
	public void test9(){
		DoubleSummaryStatistics dss = employes.stream()
				.collect(Collectors.summarizingDouble(Employee::getSalary));
		System.out.println(dss.getSum());
		System.out.println(dss.getAverage());
		System.out.println(dss.getMax());
	}
	
	// 連線字串
	@Test
	public void test10(){
		String str = employes.stream()
				.map(Employee::getName)
				.collect(Collectors.joining("," , "----", "----"));	
		System.out.println(str);
	}
}

相關推薦

關於CUDA兩種API:Runtime API 和 Driver API

ive uda ++ etime bsp con spa runt cuda CUDA 眼下有兩種不同的 API:Runtime API 和 Driver API,兩種 API 各有其適用的範圍。高級API(cuda_runtime.h)是一種C

SOA與基於CDIF的API的聯動

網絡協議 sca 流行 大發 一致性 ice 們的 硬件 形象 幾千年來,巴別塔的故事一直是人類面對的一個核心的困境。為了交流和溝通我們人類創造出語言,但溝通與交流仍然存在障礙……相同語言之間的溝通依語境的不同,尚且存在巨大的鴻溝,

身份證歸屬地查詢免費api接口代碼

stat print instance private auth content dom c99 first 描寫敘述 :依據身份證編號 查詢歸屬地信息。 身份證實體類: package org.wx.xhelper.model; /** * 身份證實體類 * @

kafka----kafka API(java版本)

spring mvc+my batis dubbo+zookeerper kafka restful redis分布式緩存 Apache Kafka包含新的Java客戶端,這些新的的客戶端將取代現存的Scala客戶端,但是為了兼容性,它們仍將存在一段時間。可以通過一些單獨的jar包調用這些客

RESTful API 設計指南

head 簡單 option eat set 取出 tro 其他 first   網絡應用程序,分為前端和後端兩個部分。當前的發展趨勢,就是前端設備層出不窮(手機、平板、桌面電腦、其他專用設備……)。   因此,必須有一種統一的機制,方便不同的前端設備與後端進行通信。這

微信小程序 -- 前端技術API手冊

開發 其他 log 關註 bsp 首頁 nbsp 補充 興趣 小時候隨手拿著英語小本子,在廁所或者路上隨時翻看的場景大家還記得嗎? 現在它有回來了,本次工程主要收錄前端各項技術API,整合在微信小程序中,在首頁選擇要學習的技術就可以進到相

saltstack api wheel模塊報錯HTTP/1.1 401 Unauthorized

saltstack api saltapi salt-api報錯 當使用saltstack api調用wheel模塊的時候會出現沒有權限的報錯[[email protected]/* */ ~]# curl -k -v https://localhost:8000 -H "Ac

Yii2 Restful Api 401

原因 數據 app -s style font code ont ram 采用Yii2 Restful Api方式為APP提供數據,默認你已經做好了所有的編碼和配置工作。采用Postman測試接口: 出現這個畫面的一個可能原因是:access_token的寫法有誤,如果你

HBase1.0以上版本號的API改變

reg hbase value col min sea ron factor valueof HBase1.0以上版本號已經廢棄了 HTableInterface,HTable,HBaseAdmin等API的使用。新增了一些API來實現之前的功能: Connect

Outlook API

set 接口 使用 一次 tde creat calendar 清單 object 1、簡介 若要從Outlook 外控制Outlook對象,必須在編寫代碼的工程中建立對Outlook對象庫的引用。 1.1 Outlook Application說明: 代表整個Micro

進階之路(基礎篇) - 011 arduino api基礎手冊

異或 change 可用 算術運算符 chan 程序結構 換算 是否 關閉 arduino 函數 api 程序結構 在Arduino中, 標準的程序入口main函數在內部被定義, 用戶只需要關心以下兩個函數:void setup()void loop()setup() 函數

在ASP.NET Core MVC中構建簡單 Web Api

程序 Getting Started在 ASP.NET Core MVC 框架中,ASP.NET 團隊為我們提供了一整套的用於構建一個 Web 中的各種部分所需的套件,那麽有些時候我們只需要做一個簡單的 Web Api 程序怎麽辦呢?在 GitHub 中的 ASP.NET Core MVC 源碼裏面,我

C++傳智筆記(6):socket客戶端發送報文接受報文的api接口

內存泄露 rcp 分配內存 strcpy light cpp tac 第三方 _file__ #define _CRT_SECURE_NO_WARNINGS #include "stdio.h" #include "stdlib.h" #include "string.

Asp.net Web Api 解決跨域問題

asp oss ros ner div exec space out color using System; using System.Collections.Generic; using System.Linq; using System.Web; using Syst

天津政府應急系統之GIS一張圖(arcgis api for flex)解說(三)顯示地圖坐標系模塊

image blur rda plain 讀取 else important baseline pat config.xml文件的配置例如以下: 1 2 <widget left="3" bottom="3" config="widg

使用Arcgis Api for Javascript 調用 本地Portal發布的WebMap

pla basemap 步驟 reat 地址 dap toc cli 配置 步驟: 安裝Arcgis Portal 10.4,Server 10.4,DataStore ,WebAdaptor for IIS,搭建arcgis api for javascript 4

kubeadm init 卡在 Created API client, waiting for the control plane to become ready

mon issues https res 出現 blog ted col journal 執行 kubeadm init 時出現卡在了 [apiclient] Created API client, waiting for the control plane to beco

API設計規範 ----Restful

creat cif created 排序 href use 服務 如果 pat    Restful API設計指南 接下來我將介紹RESTful API的設計細節,探討如何設計一套合理、好用的API 一、協議 API與用戶的通信協議,總是使用HTTPs協議。

Elasticsearch java api 基本搜索部分詳解

ocl 全部 條件 index mod data trace 服務器ip sin 版權聲明:本文非原創文章,轉載出處:http://blog.csdn.net/molong1208/article/details/50512149 一、所使用版本的介紹 使用的是ela

1.1 WEB API 在幫助文檔頁面進行測試

進行 for 技術分享 mode scrip pts itl reference ges 這篇文章http://www.cnblogs.com/landeanfen/p/5210356.html寫得比較詳細, 我就挑簡單的來說。 首先用這功能要在WEB API創建的幫助文檔