default關鍵字
在jdk1.8以前接口里面是只能有抽象方法,不能有任何方法的實現的。
在jdk1.8里面打破了這個規定,引入了新的關鍵字:default,使用default修飾方法,可以在接口里定義具體的方法
創建一個工程
代碼實現
默認方法
接口里面定義了一個默認方法,這個接口的實現類實現了這個接口之后,不用管這個default修飾的方法就可以直接調用,即接口方法的默認實現。

package com.ybchen.defaults; public interface People { void run(); void eat(); default void speak(){ System.out.println("講中國話"); } }

package com.ybchen.defaults; /** * @Description: * @Author:chenyanbin * @Date:2020/12/19 2:30 下午 * @Versiion:1.0 */ public class LaoChen implements People{ @Override public void run() { System.out.println("老陳同志在跑步"); } @Override public void eat() { System.out.println("老陳同志在吃飯"); } }

package com.ybchen.defaults; /** * @Description: * @Author:chenyanbin * @Date:2020/12/19 2:31 下午 * @Versiion:1.0 */ public class DefaultMain { public static void main(String[] args) { People people=new LaoChen(); people.eat(); people.run(); people.speak(); } }
靜態方法
調用方式:接口名.靜態方法,來訪問接口中的靜態方法
base64加解密API
舊實現方式
使用JDK里的sun.misc下的BASE64Encoder和BASE64Decoder兩個類

package com.ybchen.base64; import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; import java.io.IOException; /** * @Description:base64 加密、解密 * @Author:chenyanbin * @Date:2020/12/19 2:58 下午 * @Versiion:1.0 */ public class Base64Demo { public static void main(String[] args) throws IOException { BASE64Encoder encoder=new BASE64Encoder(); BASE64Decoder decoder=new BASE64Decoder(); String str="博客地址:https://www.cnblogs.com/chenyanbin/"; //加密 String encode = encoder.encode(str.getBytes("utf-8")); System.out.println("加密后的值:"+encode); //解密 byte[] bytes = decoder.decodeBuffer(encode); String decoderStr=new String(bytes,"utf-8"); System.out.println("解密后的值:"+decoderStr); } }
jdk1.8實現方式
在jdk1.8的java.util包中

package com.ybchen.base64; import java.io.IOException; import java.util.Base64; /** * @Description:base64 加密、解密 * @Author:chenyanbin * @Date:2020/12/19 2:58 下午 * @Versiion:1.0 */ public class Base64Demo { public static void main(String[] args) throws IOException { String str = "博客地址:https://www.cnblogs.com/chenyanbin/"; Base64.Encoder encoder = Base64.getEncoder(); Base64.Decoder decoder = Base64.getDecoder(); //加密 String encode = encoder.encodeToString(str.getBytes("utf-8")); System.out.println("加密后的值:" + encode); //解密 byte[] bytes = decoder.decode(encode); String decoderStr = new String(bytes, "utf-8"); System.out.println("解密后的值:" + decoderStr); } }
日期處理類(必備)
包所在的位置:java.time
核心類
- LocalDate:不包含具體時間的日期
- LocalTime:不含日期的時間
- LocalDateTime:包含日期及時間

package com.ybchen.local_date; import java.time.LocalDate; /** * @Description:LocalDate,不包含具體時間的日期 * @Author:chenyanbin * @Date:2020/12/19 4:00 下午 * @Versiion:1.0 */ public class LocalDateDemo { public static void main(String[] args) { LocalDate today = LocalDate.now(); System.out.println("今天日期:" + today); //年 System.out.println("現在是那年:" + today.getYear()); //月 System.out.println("現在是那月(英文):" + today.getMonth()); System.out.println("現在是那月(數字):" + today.getMonthValue()); //這月的那一天 System.out.println("現在是這月的那天:" + today.getDayOfMonth()); //現在是周幾 System.out.println("現在是周幾" + today.getDayOfWeek()); //現在是這年的第幾天 System.out.println("現在是這年的第幾天:" + today.getDayOfYear()); //加一年 System.out.println("加一年:"+today.plusYears(1)); //加一月 System.out.println("加一月:"+today.plusMonths(1)); //加一天 System.out.println("加一天:"+today.plusDays(1)); //減一年 System.out.println("減一年:"+today.minusYears(1)); //減一月 System.out.println("減一月:"+today.minusMonths(1)); //減一天 System.out.println("減一天:"+today.minusDays(1)); //減一周 System.out.println("減一周"+today.minusWeeks(1)); //日期比較,是否在某年之后 LocalDate plusYearDate = today.plusYears(1); System.out.println("是否在某年之后:"+today.isAfter(plusYearDate)); //日期比較,兩個日期對象是否相等 System.out.println("兩個日期是否相等:"+today.isEqual(plusYearDate)); } }

package com.ybchen.local_date; import java.time.Duration; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; /** * @Description:日期格式化 * @Author:chenyanbin * @Date:2020/12/19 11:52 下午 * @Versiion:1.0 */ public class LocalDateTimeFormatDemo { public static void main(String[] args) { //日期格式化 LocalDateTime localDateTime = LocalDateTime.now(); System.out.println(localDateTime); DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); System.out.println("格式化后的日期格式:" + localDateTime.format(dateTimeFormatter)); //獲取指定的日期時間對象 LocalDateTime ldt = LocalDateTime.of(2020, 12, 19, 11, 59, 59); System.out.println("獲取指定日期時間對象:" + ldt); //計算日期時間差 LocalDateTime toDay = LocalDateTime.now(); System.out.println(toDay); LocalDateTime changeDate = LocalDateTime.of(2020, 12, 29, 11, 59, 59); System.out.println(changeDate); //相差多少天 Duration duration = Duration.between(toDay, changeDate); System.out.println("相差多少天:"+ duration.toDays()); System.out.println("相差多少小時:"+duration.toHours()); System.out.println("相差多少分鍾:"+duration.toMinutes()); System.out.println("相差多少毫秒數:"+duration.toMillis()); System.out.println("相差的納秒數:"+duration.toNanos()); } }
Optional類
作用
-
空指針異常(NPE)
演示

package com.ybchen.opt; import java.util.Optional; /** * @Description: * @Author:chenyanbin * @Date:2020/12/20 12:15 上午 * @Versiion:1.0 */ public class OptionDemo { public static void main(String[] args) { Student student=null; // Student student=new Student("1","2"); //null值作為參數傳遞進去,會拋異常 // Optional<Student> optStudent = Optional.of(student); // //如果對象即可能是null也可能是非null,應該使用ofNullable // Optional<Student> optStudent2 = Optional.ofNullable(student); // //isPresent如果不為null時,返回true // if (optStudent2.isPresent()){ // System.out.println("不為null"); // //獲取泛型中的值 // Student student2 = optStudent2.get(); // System.out.println(student2); // }else { // System.out.println("為null"); // } // //兜底orElse方法 Student student3 = new Student("1", "2"); Student student1 = Optional.ofNullable(student).orElse(student3); System.out.println(student1); } }
Lambda表達式
語法
(parameters) -> expression
或
(parameters) ->{ statements; }
重要特征
- 可選類型聲明:不需要聲明參數類型,編譯器可以統一識別參數值
- 可選的參數圓括號:一個參數無需定義圓括號,但多個參數需要定義圓括號
- 可選的大括號:如果主題包含了一個語句,就不需要使用大括號
- 可選的返回關鍵字:如果主體只有一個表達式返回值則編譯器會自動返回值,大括號需要指明表達式返回了一個數值。
本質
Lambda表達式的實現方式本質是“以匿名內部類的方法”進行實現,重構現有臃腫代碼,更高的開發效率。
package com.ybchen.lambda; import java.util.Arrays; import java.util.Collections; import java.util.List; /** * @Description:lambda代碼演示 * @Author:chenyanbin * @Date:2020/12/20 11:16 上午 * @Versiion:1.0 */ public class LambdaDemo { public static void main(String[] args) { //使用多線程打印一句話 //jdk1.8之前 new Thread(new Runnable() { @Override public void run() { System.out.println("博客地址:https://www.cnblogs.com/chenyanbin/"); } }).start(); //jdk1.8之后需 new Thread(() -> System.out.println("博客地址:https://www.cnblogs.com/chenyanbin/")).start(); //List排序 List<String> list= Arrays.asList("a","f","b","c"); //jdk1.8之前排序:Comparator // Collections.sort(list, new Comparator<String>() { // @Override // public int compare(String o1, String o2) { // return o1.compareTo(o2); // } // }); // System.out.println(list); //jdk 1.8 lambda排序 Collections.sort(list,(o1, o2)->o1.compareTo(o2)); System.out.println(list); } }
自定義Lambda接口編程
- 定義一個函數式接口,需要標注此接口:@FunctionalInterface,否則萬一團隊成員在接口上加了其他方法則容易出現故障
- 編寫一個方法,輸入需要操作的數據和接口
- 在調用方法時傳入數據和lambda表達式,用來操作數據
需求
定義一個可以使用加減乘除的接口,以前的話,需要定義4個接口,現在只需要定義一個即可。
代碼實現

package com.ybchen.lambda; @FunctionalInterface //R:return;T:參數 public interface OperatorFunction<R,T> { R operator(T t1,T t2); }

package com.ybchen.lambda; /** * @Description:四則運算 * @Author:chenyanbin * @Date:2020/12/20 1:35 下午 * @Versiion:1.0 */ public class OperatorDemo { public static void main(String[] args) { System.out.println("加法:" + operator(20, 5, (x, y) -> x + y)); System.out.println("減法:" + operator(20, 5, (x, y) -> x - y)); System.out.println("乘法:" + operator(20, 5, (x, y) -> x * y)); System.out.println("除法:" + operator(20, 5, (x, y) -> x / y)); } private static Integer operator(Integer x, Integer y, OperatorFunction<Integer, Integer> operatorFunction) { return operatorFunction.operator(x, y); } }
JDK 1.8 新增加的函數接口
文檔地址:點我直達
函數式編程Function
- 傳入一個值經過函數的計算返回另一個值
- T:入參類型,R:出參類型
- 調用方法:R apply(T t)
函數式編程Bifunction
- Function只能接收一個參數, 如果要傳遞兩個參數,則用Bifunction

package com.ybchen.lambda; import java.util.function.BiFunction; /** * @Description:BiFunction * @Author:chenyanbin * @Date:2020/12/20 2:27 下午 * @Versiion:1.0 */ public class BiFunctionDemo { public static void main(String[] args) { System.out.println("加法:" + operator(20, 5, (x, y) -> x + y)); System.out.println("減法:" + operator(20, 5, (x, y) -> x - y)); System.out.println("乘法:" + operator(20, 5, (x, y) -> x * y)); System.out.println("除法:" + operator(20, 5, (x, y) -> x / y)); } private static Integer operator(Integer x, Integer y, BiFunction<Integer,Integer,Integer> biFunction){ return biFunction.apply(x,y); } }
函數式編程Consumer
- 有入參,無返回值
- 用途:因為沒有出參,常用於打印、發送短信等消費動作

package com.ybchen.lambda; import java.util.function.Consumer; /** * @Description:Consumer * @Author:chenyanbin * @Date:2020/12/20 2:35 下午 * @Versiion:1.0 */ public class ConsumerDemo { public static void main(String[] args) { Consumer<String> consumer=(phone)->{ System.out.println("手機號:"+phone); System.out.println("發送短信成功"); }; sendMsg("11111",consumer); } private static void sendMsg(String phone, Consumer<String> consumer){ consumer.accept(phone); } }
jdk源碼中的使用
函數式編程Supplier
- 供給型接口:無入參,有返回值
- T:出參類型,沒有入參
- 用途:泛型一定和方法的返回值類型是一種類型,如果需要獲得一個數據,並且不需要傳入參數,可以使用Supplier接口,例如:無參的工廠方法,即工廠設計模式創建(點我直達)對象,簡單來說就是 提供者,方便程序的解耦,(給你個眼神自己體會)

package com.ybchen.lambda; import java.util.function.Supplier; /** * @Description:Supplier功能演示 * @Author:chenyanbin * @Date:2020/12/20 8:30 下午 * @Versiion:1.0 */ public class SupplierDemo { public static void main(String[] args) { Student2 stu=getStudent2(); System.out.println(stu); } private static Student2 getStudent2(){ Supplier<Student2> supplier=()->{ Student2 student2=new Student2(); student2.setId("2"); student2.setName("默認名稱"); return student2; }; return supplier.get(); } } class Student2{ private String id; private String name; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "Student2{" + "id='" + id + '\'' + ", name='" + name + '\'' + '}'; } }
函數式編程Predicate
- 斷言型接口:有入參,有返回值i,返回值類型確定是Boolean
- T:入參類型;出參類型是Boolean
- 調用方法:boolean test(T t)
- 用途:接收一個參數,用於判斷是否滿足一定的條件,過濾數據

package com.ybchen.lambda; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.function.Predicate; /** * @Description:Predicate斷言演示 * @Author:chenyanbin * @Date:2020/12/20 8:56 下午 * @Versiion:1.0 */ public class PredicateDemo { public static void main(String[] args) { List<Integer> list= Arrays.asList(1,2,3,4,5,6); List<Integer> fileter = fileter(list, num -> num % 2 == 0); fileter.forEach(num-> System.out.println(num)); } private static List<Integer> fileter(List<Integer> list, Predicate<Integer> predicate){ List<Integer> resultList=new ArrayList<>(); for (Integer i:list){ if (predicate.test(i)){ resultList.add(i); } } return resultList; } }
構造函數引用
jdk1.8之前,方法調用,對象.方法名,或者 類名.方法名
jdk1.8提供了另外一種調用方式::
方法引用時一種更簡潔易懂的lambda表達式,操作符是雙冒號“::”,用來直接訪問類或者實例已經存在的方法或構造方法。
- 靜態方法,ClassName::methodName
- 實例方法,Intance::methodName
- 構造函數,類名::new
package com.ybchen.lambda; import java.util.function.BiFunction; import java.util.function.Function; /** * @Description:構造函數的引用 * @Author:chenyanbin * @Date:2020/12/20 9:33 下午 * @Versiion:1.0 */ public class ConstructionDemo { public static void main(String[] args) { //使用雙冒號::,來構造靜態函數的引用 Function<String,Integer> func=Integer::parseInt; System.out.println(func.apply("123") instanceof Integer); //使用雙冒號::,來構造非靜態函數的引用 String content="博客地址:https://www.cnblogs.com/chenyanbin/"; Function<Integer,String> func2=content::substring; String result = func2.apply(2); System.out.println(result); //構造函數 Function<String,Student3> func3=Student3::new; Student3 stu3 = func3.apply("1"); System.out.println(stu3); BiFunction<String,String,Student3> func4=Student3::new; Student3 stu4 = func4.apply("1", "老陳"); System.out.println(stu4); } } class Student3{ private String id; private String name; public Student3() { } public Student3(String id) { this.id = id; } public Student3(String id, String name) { this.id = id; this.name = name; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "Student3{" + "id='" + id + '\'' + ", name='" + name + '\'' + '}'; } }
true 地址:https://www.cnblogs.com/chenyanbin/ Student3{id='1', name='null'} Student3{id='1', name='老陳'} Process finished with exit code 0
集合框架
什么是Stream?
Stream中文稱為“流”,通過將集合轉換為“流”的元素隊列,通過聲明性方式,能夠對集合中的每個元素進行一系列並行或串行的流水線操作
map和filter函數
map
- 將流中的每一個元素T映射為R
- 應用場景:轉換對象,如:DO對象轉換為DTO對象

package com.ybchen.stream; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; /** * @Description:map功能演示 * @Author:chenyanbin * @Date:2020/12/20 10:15 下午 * @Versiion:1.0 */ public class MapDemo { public static void main(String[] args) { List<String> list= Arrays.asList("老陳","老李","老王"); List<String> collect = list.stream().map(name -> "我叫:" + name).collect(Collectors.toList()); collect.forEach(name-> System.out.println(name)); } }

package com.ybchen.stream; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; /** * @Description:map,do轉dto功能演示 * @Author:chenyanbin * @Date:2020/12/20 10:48 下午 * @Versiion:1.0 */ public class MapDemo2 { public static void main(String[] args) { List<User> list= Arrays.asList(new User("1","老陳","123"), new User("1","老王","123456")); List<UserDTO> collect = list.stream().map(obj -> new UserDTO(obj.getId(), obj.getName())).collect(Collectors.toList()); collect.forEach(obj-> System.out.println(obj)); } } class User{ private String id; private String name; private String pwd; public User() { } public User(String id, String name, String pwd) { this.id = id; this.name = name; this.pwd = pwd; } public String getId() { return id; } public String getName() { return name; } public String getPwd() { return pwd; } } class UserDTO{ private String userId; private String userName; public UserDTO(String userId, String userName) { this.userId = userId; this.userName = userName; } @Override public String toString() { return "UserDTO{" + "userId='" + userId + '\'' + ", userName='" + userName + '\'' + '}'; } }
filter
- 應用:用於設置條件的過濾

package com.ybchen.stream; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; /** * @Description:Filter功能演示,過濾對2取余等於0的元素 * @Author:chenyanbin * @Date:2020/12/20 10:19 下午 * @Versiion:1.0 */ public class FilterDemo { public static void main(String[] args) { List<Integer> list= Arrays.asList(1,2,3,4,5,6,7,8,9,10); List<Integer> collect = list.stream().filter(num -> num % 2 == 0).collect(Collectors.toList()); collect.forEach(num-> System.out.println(num)); } }
limit、skip、sorted函數
sorted
- 對流進行自然排序,其中的元素必須實現Comparable接口
package com.ybchen.stream; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; /** * @Description: * @Author:chenyanbin * @Date:2020/12/20 11:23 下午 * @Versiion:1.0 */ public class SortedDemo { public static void main(String[] args) { List<String> list= Arrays.asList("SpringBoot","SpringMvc","Dubbo","SpringCloud"); //默認升序 List<String> collect = list.stream().sorted().collect(Collectors.toList()); System.out.println(collect); System.out.println("-----------"); //自定義排序,根據長度升序 List<String> collect1 = list.stream().sorted(Comparator.comparing(obj -> obj.length())).collect(Collectors.toList()); System.out.println(collect1); //自定義排序,根據長度降序 List<String> collect2 = list.stream().sorted(Comparator.comparing(obj -> obj.length(),Comparator.reverseOrder())).collect(Collectors.toList()); System.out.println(collect2); //方法引用的玩法 List<String> collect3 = list.stream().sorted(Comparator.comparing(String::length,Comparator.reverseOrder())).collect(Collectors.toList()); System.out.println(collect3); } }
limit
- 截斷流使用最多只包含指定數量的元素

package com.ybchen.stream; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; /** * @Description:獲取前3個元素 * @Author:chenyanbin * @Date:2020/12/20 11:36 下午 * @Versiion:1.0 */ public class LimitDemo { public static void main(String[] args) { List<String> list= Arrays.asList("SpringBoot","SpringMvc","Dubbo","SpringCloud"); List<String> collect = list.stream().limit(3).collect(Collectors.toList()); System.out.println(collect); } }
skip
- 跳過多少個元素

package com.ybchen.stream; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; /** * @Description:跳過前2個元素 * @Author:chenyanbin * @Date:2020/12/20 11:41 下午 * @Versiion:1.0 */ public class SkipDemo { public static void main(String[] args) { List<String> list= Arrays.asList("SpringBoot","SpringMvc","Dubbo","SpringCloud"); List<String> collect = list.stream().skip(2).collect(Collectors.toList()); System.out.println(list); System.out.println(collect); } }
allMatch和anyMatch函數
allMatch
- 檢查是否匹配所有元素,只有全部符合才返回true

package com.ybchen.stream; import java.util.Arrays; import java.util.List; /** * @Description: * @Author:chenyanbin * @Date:2020/12/20 11:46 下午 * @Versiion:1.0 */ public class AllMatchDemo { public static void main(String[] args) { List<String> list= Arrays.asList("SpringBoot","SpringMvc","SDubbo","SpringCloud"); boolean b = list.stream().allMatch(str -> str.startsWith("S")); System.out.println(b); } }
anyMatch
- 檢查是否至少匹配一個元素

package com.ybchen.stream; import java.util.Arrays; import java.util.List; /** * @Description:至少匹配一個返回true * @Author:chenyanbin * @Date:2020/12/20 11:48 下午 * @Versiion:1.0 */ public class AnyMatchDemo { public static void main(String[] args) { List<String> list= Arrays.asList("SpringBoot","SpringMvc","Dubbo","SpringCloud"); boolean b = list.stream().anyMatch(str -> str.startsWith("s")); System.out.println(b); } }
max和min函數
- 求最大、最小

package com.ybchen.stream; import java.util.Arrays; import java.util.List; /** * @Description:求最大、最小 * @Author:chenyanbin * @Date:2020/12/21 12:01 上午 * @Versiion:1.0 */ public class MaxAndMinDemo { public static void main(String[] args) { List<String> list= Arrays.asList("SpringBoot","SpringMvc","Dubbo","SpringCloud"); String s = list.stream().max((str1, str2) -> str1.length() - str2.length()).get(); System.out.println(s); String s2 = list.stream().min((str1, str2) -> str1.length() - str2.length()).get(); System.out.println(s2); } }
distinct函數

package com.ybchen.stream; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; /** * @Description:對元素去重 * @Author:chenyanbin * @Date:2020/12/20 11:54 下午 * @Versiion:1.0 */ public class DistinctDemo { public static void main(String[] args) { List<String> list= Arrays.asList("SpringBoot","SpringMvc","Dubbo","SpringCloud","Dubbo"); System.out.println(list); List<String> collect = list.stream().distinct().collect(Collectors.toList()); System.out.println(collect); } }
並行流parallelStream
- 集合做重復的操作,如果使用串行執行會相當耗時,因此一般會采用多線程來加快,java 8的paralleStream用fork/join框架提供了並發執行能力

package com.ybchen.stream; import java.util.Arrays; import java.util.List; /** * @Description:ParallelStream串行流演示 * @Author:chenyanbin * @Date:2020/12/21 9:41 下午 * @Versiion:1.0 */ public class ParallelStreamDemo { public static void main(String[] args) { List<Integer> list= Arrays.asList(1,2,3,4,5,6,7,8); list.stream().forEach(System.out::println); System.out.println("==============="); list.parallelStream().forEach(System.out::println); } }
注意事項
- parallelStream里面使用外部變量時,會出現線程安全問題,集合一定要使用線程安全集合
reduce操作
- 根據一定的規則將Stream中的元素進行計算后返回一個唯一的值
常用方法一

package com.ybchen.stream; import java.util.stream.Stream; /** * @Description:Reduce功能演示 * @Author:chenyanbin * @Date:2020/12/21 10:01 下午 * @Versiion:1.0 */ public class ReduceDemo { public static void main(String[] args) { Integer sum = Stream.of(1, 2, 3, 4).reduce((num1, num2) -> num1 + num2).get(); System.out.println(sum); } }
求一堆數的最大值

package com.ybchen.stream; import java.util.stream.Stream; /** * @Description:Reduce功能演示 * @Author:chenyanbin * @Date:2020/12/21 10:01 下午 * @Versiion:1.0 */ public class ReduceDemo { public static void main(String[] args) { //求一堆數的最大值 Integer maxValue = Stream.of(1, 33, 5, 6, 2).reduce((num1, num2) -> num1 > num2 ? num1 : num2).get(); System.out.println(maxValue); } }
常用方法二
提供一個初始值,進行數據累加

package com.ybchen.stream; import java.util.stream.Stream; /** * @Description:Reduce功能演示 * @Author:chenyanbin * @Date:2020/12/21 10:01 下午 * @Versiion:1.0 */ public class ReduceDemo { public static void main(String[] args) { //提供一個初始值,對數據進行累加操作 Integer sum = Stream.of(1, 2, 3, 4).reduce(100,(num1, num2) -> num1 + num2); System.out.println(sum); } }
收集器和集合統計
collector收集器
package com.ybchen.stream; import java.util.*; import java.util.stream.Collectors; /** * @Description: * @Author:chenyanbin * @Date:2020/12/21 10:45 下午 * @Versiion:1.0 */ public class CollectorDemo { public static void main(String[] args) { List<Integer> list= Arrays.asList(1,2,3,4,5); List<Integer> collect = list.stream().collect(Collectors.toList()); Set<Integer> collect1 = list.stream().collect(Collectors.toCollection(TreeSet::new)); List<Integer> collect2 = list.stream().collect(Collectors.toCollection(LinkedList::new)); } }
joining函數
- 拼接函數,Collectors.joining

package com.ybchen.stream; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; /** * @Description:字符串拼接 * @Author:chenyanbin * @Date:2020/12/21 10:51 下午 * @Versiion:1.0 */ public class JoinDemo { public static void main(String[] args) { List<String> list= Arrays.asList("a","b","c","d"); String collect = list.stream().collect(Collectors.joining()); System.out.println(collect); System.out.println("=========="); String collect2 = list.stream().collect(Collectors.joining("_")); System.out.println(collect2); System.out.println("=========="); String collect3 = list.stream().collect(Collectors.joining("_","(",")")); System.out.println(collect3); System.out.println("========="); String result = Stream.of("a", "b", "c", "d").collect(Collectors.joining(",", "「", "」")); System.out.println(result); } }
partitioningBy分組
- Collectors.partitioningBy分組,key是boolean類型

package com.ybchen.stream; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.stream.Collectors; /** * @Description: * @Author:chenyanbin * @Date:2020/12/21 11:01 下午 * @Versiion:1.0 */ public class PartitioningByDemo { public static void main(String[] args) { List<Integer> list= Arrays.asList(1,2,3,4,5,6); Map<Boolean, List<Integer>> collect = list.stream().collect(Collectors.partitioningBy(num -> num % 2 == 0)); System.out.println(collect); } }
groupby分組
- 分組,Collectors.groupingBy()

package com.ybchen.stream; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.stream.Collectors; /** * @Description:根據學生所在的省份,進行分組 * @Author:chenyanbin * @Date:2020/12/21 11:05 下午 * @Versiion:1.0 */ public class GroupByDemo { public static void main(String[] args) { List<Student> list= Arrays.asList( new Student("老陳","上海"), new Student("老王","北京"), new Student("老李","上海"), new Student("老趙","廣東")); Map<String, List<Student>> collect = list.stream().collect(Collectors.groupingBy(obj -> obj.getProvince())); System.out.println(collect); } } class Student{ private String name; private String province; public Student(String name, String province) { this.name = name; this.province = province; } public String getProvince() { return province; } @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", province='" + province + '\'' + '}'; } }
counting集合統計
- 聚合函數進行統計查詢,分組后統計個數
- Collectors.counting():統計元素個數
需求:統計省份的人數

package com.ybchen.stream; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.stream.Collectors; /** * @Description:根據學生所在的省份,進行分組 * @Author:chenyanbin * @Date:2020/12/21 11:05 下午 * @Versiion:1.0 */ public class GroupByDemo { public static void main(String[] args) { List<Student> list= Arrays.asList( new Student("老陳","上海"), new Student("老王","北京"), new Student("老李","上海"), new Student("老趙","廣東")); Map<String, Long> collect = list.stream().collect(Collectors.groupingBy(obj -> obj.getProvince(), Collectors.counting())); System.out.println(collect); } } class Student{ private String name; private String province; public Student(String name, String province) { this.name = name; this.province = province; } public String getProvince() { return province; } @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", province='" + province + '\'' + '}'; } }