一 java8 lambda表達式用法
1 什么是lambda表達式
Lambda表達式有兩個特點:一是匿名函數,二是可傳遞。
匿名函數的應用場景是:
通常是在需要一個函數,但是又不想費神去命名一個函數的場合下使用Lambda表達式。lambda表達式所表示的匿名函數的內容應該是很簡單的,如果復雜的話,干脆就重新定義一個函數了,使用lambda就有點過於執拗了。
可傳遞使用場景是:
就是將Lambda表達式傳遞給其他的函數,它當做參數,Lambda作為一種更緊湊的代碼風格,使Java的語言表達能力得到提升。
2 lambda表達式語法
Lambda表達式在Java語言中引入了一個新的語法元素和操作符。這個操作符為"->",該操作符被稱為Lambda操作符或箭頭操作符,它將Lambda分為兩個部分:
左側:指定了Lambda表達式所需要的所有參數
右側:指定了Lambda體,即Lambda表達式所要執行的功能。
在函數式編程語言中,Lambda表達式的類型是函數。而在Java中,Lambda表達式是對象,它們必須依附於一類特別的對象類型——函數式接口(Functional Interface)。
常見的語法格式:
語法格式一:無參,無返回值,Lambda體只需要一條語句。
Runnable r = () -> System.out.println("Hello Lambda!");
語法格式二:Lambda需要一個參數
Consumer<String> con = (x) -> System.out.println(x);
語法格式三:Lambda只需要一個參數時,參數的小括號可以省略
Consumer<String> con = x -> System.out.println(x);
語法格式四:Lambda需要兩個參數,並且有返回值
Comparator<Integer> com = (x, y) -> { System.out.println("函數式接口"); return Integer.compare(x, y); };
語法格式五:當Lambda體只有一條語句時,return與大括號可以省略
Comparator<Integer> com = (x, y) -> Integer.compare(x, y);
語法格式六:數據類型可以省略,因為可由編譯器推斷得出,稱為類型推斷
BinaryOperator<Long> operator = (Long x, Long y) -> { System.out.println("實現函數接口方法"); return x + y; };
二 函數式接口
如果一個接口中,有且只有一個抽象的方法(Object類中的方法不包括在內),那這個接口就可以被看做是函數式接口。例如Runnable接口就是一個函數式接口:
@FunctionalInterface public interface Runnable { public abstract void run(); }
另外,如下接口:
@FunctionalInterface
public interface MyInterface { void test(); String toString(); }
MyInterface這也是一個函數式接口,因為toString()是Object類中的方法,只是在這里進行了復寫,不會增加接口中抽象方法的數量。
函數式接口實例的創建可以有三種方式:
1.lambda表達式
如果使用lambda表達式來創建一個函數式接口實例,那這個lambda表達式的入參和返回必須符合這個函數式接口中唯一的抽象方法的定義
list.forEach(item -> System.out.println(item));
2.方法引用
list.forEach(System.out::println);
方法引用的語法是 對象::方法名
3.構造方法引用
list.forEach(Test1::new); Test1(Integer i){ System.out.println(i); }
構造方法引用的語法是:類名::new
我們給Test1新添加了一個構造方法,該構造方法接收一個參數,不返回值
例如,java8以前,創建一個線程執行Runnable接口的方式一般如下:
new Thread(new Runnable() { @Override public void run() { System.out.println("線程執行"); } }).start();
使用函數式編程即可使用如下方式:
new Thread(() -> System.out.println("線程執行")).start();
java8提供了一系列常見的函數式接口,最常用的如下幾個:
Function:提供任意一種類型的參數,返回另外一個任意類型返回值。 R apply(T t);
Consumer:提供任意一種類型的參數,返回空值。 void accept(T t);
Supplier:參數為空,得到任意一種類型的返回值。T get();
Predicate:提供任意一種類型的參數,返回boolean返回值。boolean test(T t);
三 java8 stream用法
1 初步認識

舉個例子:
@Before public void init() { random = new Random(); stuList = new ArrayList<Student>() { { for (int i = 0; i < 100; i++) { add(new Student("student" + i, random.nextInt(50) + 50)); } } }; } public class Student { private String name; private Integer score; //-----getters and setters----- } //1列出班上超過85分的學生姓名,並按照分數降序輸出用戶名字 @Test public void test1() { List<String> studentList = stuList.stream() .filter(x->x.getScore()>85) .sorted(Comparator.comparing(Student::getScore).reversed()) .map(Student::getName) .collect(Collectors.toList()); System.out.println(studentList); }
列出班上分數超過85分的學生姓名,並按照分數降序輸出用戶名字,在java8之前我們需要三個步驟:
1)新建一個List<Student> newList,在for循環中遍歷stuList,將分數超過85分的學生裝入新的集合中
2)對於新的集合newList進行排序操作
3)遍歷打印newList
這三個步驟在java8中只需要兩條語句,如果僅僅需要打印,不需要保存新生產list的話實際上只需要一條,是不是非常方便。
2 stream的特性
stream主要具有如下三點特性,在之后我們會對照着詳細說明
(1)stream不存儲數據
(2)stream不改變源數據
(3)stream的延遲執行特性
通常我們在數組或集合的基礎上創建stream,stream不會專門存儲數據,對stream的操作也不會影響到創建它的數組和集合,對於stream的聚合、消費或收集操作只能進行一次,再次操作會報錯,如下代碼:
@Test public void test1(){ Stream<String> stream = Stream.generate(()->"user").limit(3); stream.forEach(System.out::println); stream.forEach(System.out::println); }
輸出結果如下:
user user user java.lang.IllegalStateException: stream has already been operated upon or closed
程序在正常完成一次打印工作后報錯。
stream的操作是延遲執行的,在列出班上超過85分的學生姓名例子中,在collect方法執行之前,filter、sorted、map方法還未執行,只有當collect方法執行時才會觸發之前轉換操作
看如下代碼:
public boolean filter(Student s) { System.out.println("begin compare"); return s.getScore() > 85; } @Test public void test() { Stream<Student> stream = stuList.stream().filter(this::filter); System.out.println("split-------------------------------------"); List<Student> studentList = stream.collect(toList()); System.out.println(studentList); }
打印結果如下:
split-------------------------------------
begin compare
begin compare
begin compare
begin compare
begin compare
begin compare
begin compare
由此可以看出,在執行完filter時,沒有實際執行filter中的方法,而是等到執行collect時才會執行,即是延遲執行的。
List<String> wordList; @Before public void init() { wordList = new ArrayList<String>() { { add("a"); add("b"); add("c"); add("d"); add("e"); add("f"); add("g"); } }; } /** * 延遲執行特性,在聚合操作之前都可以添加相應元素 */ @Test public void test() { Stream<String> words = wordList.stream(); wordList.add("END"); long n = words.distinct().count(); System.out.println(n); }
最后打印的結果是8。如下代碼是錯誤的:
/** * 延遲執行特性,會產生干擾 * nullPointException */ @Test public void test2(){ Stream<String> words1 = wordList.stream(); words1.forEach(s -> { System.out.println("s->"+s); if (s.length() < 4) { System.out.println("select->"+s); wordList.remove(s); System.out.println(wordList); } }); }
結果會報NPE空指針異常。
3 創建Stream
(1)通過數組創建
/** * 通過數組創建流 */ @Test public void testArrayStream(){ //1.通過Arrays.stream //1.1基本類型 int[] arr = new int[]{1,2,34,5}; IntStream intStream = Arrays.stream(arr); //1.2引用類型 Student[] studentArr = new Student[]{new Student("s1",29),new Student("s2",27)}; Stream<Student> studentStream = Arrays.stream(studentArr); //2.通過Stream.of Stream<Integer> stream1 = Stream.of(1,2,34,5,65); //注意生成的是int[]的流 Stream<int[]> stream2 = Stream.of(arr,arr); stream2.forEach(System.out::println); }
(2)通過集合創建流
/** * 通過集合創建流 */ @Test public void testCollectionStream(){ List<String> strs = Arrays.asList("11212","dfd","2323","dfhgf"); //創建普通流 Stream<String> stream = strs.stream(); //創建並行流(即多個線程處理) Stream<String> stream1 = strs.parallelStream(); }
@Test public void testEmptyStream(){ //創建一個空的stream Stream<Integer> stream = Stream.empty(); }
@Test public void testUnlimitStream(){ //創建無限流,通過limit提取指定大小 Stream.generate(()->"number"+new Random().nextInt()).limit(100).forEach(System.out::println); Stream.generate(()->new Student("name",10)).limit(20).forEach(System.out::println); }
/** * 產生規律的數據 */ @Test public void testUnlimitStream1(){ Stream.iterate(0,x->x+1).limit(10).forEach(System.out::println); Stream.iterate(0,x->x).limit(10).forEach(System.out::println); //Stream.iterate(0,x->x).limit(10).forEach(System.out::println);與如下代碼意思是一樣的 Stream.iterate(0, UnaryOperator.identity()).limit(10).forEach(System.out::println); }
4 對stream的操作
(1)map:轉換流,將一種類型的流轉換為另外一種流
/** * map把一種類型的流轉換為另外一種類型的流 * 將String數組中字母轉換為大寫 */ @Test public void testMap() { String[] arr = new String[]{"yes", "YES", "no", "NO"}; Arrays.stream(arr).map(x -> x.toLowerCase()).forEach(System.out::println); }
將所有的子串轉換為小寫字符串並打印。map接收一個Function<T, R>函數接口,R apply(T t);即接收一個參數,並且有返回值。
(2) filter:過濾流,過濾流中的元素
@Test public void testFilter(){ Integer[] arr = new Integer[]{1,2,3,4,5,6,7,8,9,10}; Arrays.stream(arr).filter(x->x>3&&x<8).forEach(System.out::println); }
filter接收一個Predicate<T>函數接口參數,boolean test(T t);即接收一個參數,返回boolean類型。
/** * flapMap:拆解流 */ @Test public void testFlapMap1() { String[] arr1 = {"a", "b", "c", "d"}; String[] arr2 = {"e", "f", "c", "d"}; String[] arr3 = {"h", "j", "c", "d"}; // Stream.of(arr1, arr2, arr3).flatMap(x -> Arrays.stream(x)).forEach(System.out::println); Stream.of(arr1, arr2, arr3).flatMap(Arrays::stream).forEach(System.out::println); }
flatMap接收一個Function<T, R>函數接口:<R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper);即入參為集合類型,返回Stream類型。
String[] arr1 = {"abc","a","bc","abcd"}; /** * Comparator.comparing是一個鍵提取的功能 * 以下兩個語句表示相同意義 */ @Test public void testSorted1_(){ /** * 按照字符長度排序 */ Arrays.stream(arr1).sorted((x,y)->{ if (x.length()>y.length()) return 1; else if (x.length()<y.length()) return -1; else return 0; }).forEach(System.out::println);
Arrays.stream(arr1).sorted(Comparator.comparing(String::length)).forEach(System.out::println); } /** * 倒序 * reversed(),java8泛型推導的問題,所以如果comparing里面是非方法引用的lambda表達式就沒辦法直接使用reversed() * Comparator.reverseOrder():也是用於翻轉順序,用於比較對象(Stream里面的類型必須是可比較的) * Comparator. naturalOrder():返回一個自然排序比較器,用於比較對象(Stream里面的類型必須是可比較的) */ @Test public void testSorted2_(){ Arrays.stream(arr1).sorted(Comparator.comparing(String::length).reversed()).forEach(System.out::println); Arrays.stream(arr1).sorted(Comparator.reverseOrder()).forEach(System.out::println); Arrays.stream(arr1).sorted(Comparator.naturalOrder()).forEach(System.out::println); } /** * thenComparing * 先按照首字母排序 * 之后按照String的長度排序 */ @Test public void testSorted3_(){ Arrays.stream(arr1).sorted(Comparator.comparing(this::com1).thenComparing(String::length)).forEach(System.out::println); } public char com1(String x){ return x.charAt(0); }
(5)提取流和組合流
@Before public void init(){ arr1 = new String[]{"a","b","c","d"}; arr2 = new String[]{"d","e","f","g"}; arr3 = new String[]{"i","j","k","l"}; } /** * limit,限制從流中獲得前n個數據 */ @Test public void testLimit(){ Stream.iterate(1,x->x+2).limit(10).forEach(System.out::println); } /** * skip,跳過前n個數據 */ @Test public void testSkip(){ // Stream.of(arr1).skip(2).limit(2).forEach(System.out::println); Stream.iterate(1,x->x+2).skip(1).limit(5).forEach(System.out::println); } /** * 可以把兩個stream合並成一個stream(合並的stream類型必須相同) * 只能兩兩合並 */ @Test public void testConcat(){ Stream<String> stream1 = Stream.of(arr1); Stream<String> stream2 = Stream.of(arr2); Stream.concat(stream1,stream2).distinct().forEach(System.out::println); }
(6)聚合操作
@Before public void init(){ arr = new String[]{"b","ab","abc","abcd","abcde"}; } /** * max、min * 最大最小值 */ @Test public void testMaxAndMin(){ Stream.of(arr).max(Comparator.comparing(String::length)).ifPresent(System.out::println); Stream.of(arr).min(Comparator.comparing(String::length)).ifPresent(System.out::println); } /** * count * 計算數量 */ @Test public void testCount(){ long count = Stream.of(arr).count(); System.out.println(count); } /** * findFirst * 查找第一個 */ @Test public void testFindFirst(){ String str = Stream.of(arr).parallel().filter(x->x.length()>3).findFirst().orElse("noghing"); System.out.println(str); } /** * findAny * 找到所有匹配的元素 * 對並行流十分有效 * 只要在任何片段發現了第一個匹配元素就會結束整個運算 */ @Test public void testFindAny(){ Optional<String> optional = Stream.of(arr).parallel().filter(x->x.length()>3).findAny(); optional.ifPresent(System.out::println); } /** * anyMatch * 是否含有匹配元素 */ @Test public void testAnyMatch(){ Boolean aBoolean = Stream.of(arr).anyMatch(x->x.startsWith("a")); System.out.println(aBoolean); } @Test public void testStream1() { Optional<Integer> optional = Stream.of(1,2,3).filter(x->x>1).reduce((x,y)->x+y); System.out.println(optional.get()); }
5 Optional類型
@Test public void testOptional() { List<String> list = new ArrayList<String>() { { add("user1"); add("user2"); } }; Optional<String> opt = Optional.of("andy with u"); opt.ifPresent(list::add); list.forEach(System.out::println); }
使用Optional可以在沒有值時指定一個返回值,例如
@Test public void testOptional2() { Integer[] arr = new Integer[]{4,5,6,7,8,9}; Integer result = Stream.of(arr).filter(x->x>9).max(Comparator.naturalOrder()).orElse(-1); System.out.println(result); Integer result1 = Stream.of(arr).filter(x->x>9).max(Comparator.naturalOrder()).orElseGet(()->-1); System.out.println(result1); Integer result2 = Stream.of(arr).filter(x->x>9).max(Comparator.naturalOrder()).orElseThrow(RuntimeException::new); System.out.println(result2); }
采用Optional.empty()創建一個空的Optional,使用Optional.of()創建指定值的Optional。同樣也可以調用Optional對象的map方法進行Optional的轉換,調用flatMap方法進行Optional的迭代
@Test public void testStream1() { Optional<Student> studentOptional = Optional.of(new Student("user1",21)); Optional<String> optionalStr = studentOptional.map(Student::getName); System.out.println(optionalStr.get()); } public static Optional<Double> inverse(Double x) { return x == 0 ? Optional.empty() : Optional.of(1 / x); } public static Optional<Double> squareRoot(Double x) { return x < 0 ? Optional.empty() : Optional.of(Math.sqrt(x)); } /** * Optional的迭代 */ @Test public void testStream2() { double x = 4d; Optional<Double> result1 = inverse(x).flatMap(StreamTest7::squareRoot); result1.ifPresent(System.out::println); Optional<Double> result2 = Optional.of(4.0).flatMap(StreamTest7::inverse).flatMap(StreamTest7::squareRoot); result2.ifPresent(System.out::println); }
6 收集結果
Student[] students; @Before public void init(){ students = new Student[100]; for (int i=0;i<30;i++){ Student student = new Student("user",i); students[i] = student; } for (int i=30;i<60;i++){ Student student = new Student("user"+i,i); students[i] = student; } for (int i=60;i<100;i++){ Student student = new Student("user"+i,i); students[i] = student; } } @Test public void testCollect1(){ /** * 生成List */ List<Student> list = Arrays.stream(students).collect(Collectors.toList()); list.forEach((x)-> System.out.println(x)); /** * 生成Set */ Set<Student> set = Arrays.stream(students).collect(Collectors.toSet()); set.forEach((x)-> System.out.println(x)); /** * 如果包含相同的key,則需要提供第三個參數,否則報錯 */ Map<String,Integer> map = Arrays.stream(students).collect(Collectors.toMap(Student::getName,Student::getScore,(s,a)->s+a)); map.forEach((x,y)-> System.out.println(x+"->"+y)); } /** * 生成數組 */ @Test public void testCollect2(){ Student[] s = Arrays.stream(students).toArray(Student[]::new); for (int i=0;i<s.length;i++) System.out.println(s[i]); } /** * 指定生成的類型 */ @Test public void testCollect3(){ HashSet<Student> s = Arrays.stream(students).collect(toCollection(HashSet::new)); s.forEach(System.out::println); } /** * 統計 */ @Test public void testCollect4(){ IntSummaryStatistics summaryStatistics = Arrays.stream(students).collect(Collectors.summarizingInt(Student::getScore)); System.out.println("getAverage->"+summaryStatistics.getAverage()); System.out.println("getMax->"+summaryStatistics.getMax()); System.out.println("getMin->"+summaryStatistics.getMin()); System.out.println("getCount->"+summaryStatistics.getCount()); System.out.println("getSum->"+summaryStatistics.getSum()); }
7 分組和分片
Student[] students; @Before public void init(){ students = new Student[100]; for (int i=0;i<30;i++){ Student student = new Student("user1",i); students[i] = student; } for (int i=30;i<60;i++){ Student student = new Student("user2",i); students[i] = student; } for (int i=60;i<100;i++){ Student student = new Student("user3",i); students[i] = student; } }
/**
* 按照名稱分組
*
*/ @Test public void testGroupBy1(){ Map<String,List<Student>> map = Arrays.stream(students).collect(Collectors.groupingBy(Student::getName)); map.forEach((x,y)-> System.out.println(x+"->"+y)); } /** * 如果只有兩類,使用partitioningBy會比groupingBy更有效率,按照分數是否大於50分組 */ @Test public void testPartitioningBy(){ Map<Boolean,List<Student>> map = Arrays.stream(students).collect(Collectors.partitioningBy(x->x.getScore()>50)); map.forEach((x,y)-> System.out.println(x+"->"+y)); } /** * downstream指定類型 */ @Test public void testGroupBy2(){ Map<String,Set<Student>> map = Arrays.stream(students).collect(Collectors.groupingBy(Student::getName,Collectors.toSet())); map.forEach((x,y)-> System.out.println(x+"->"+y)); } /** * downstream 聚合操作 */ @Test public void testGroupBy3(){ /** * counting */ Map<String,Long> map1 = Arrays.stream(students).collect(Collectors.groupingBy(Student::getName,Collectors.counting())); map1.forEach((x,y)-> System.out.println(x+"->"+y)); /** * summingInt */ Map<String,Integer> map2 = Arrays.stream(students).collect(Collectors.groupingBy(Student::getName,Collectors.summingInt(Student::getScore))); map2.forEach((x,y)-> System.out.println(x+"->"+y)); /** * maxBy */ Map<String,Optional<Student>> map3 = Arrays.stream(students).collect(groupingBy(Student::getName,maxBy(Comparator.comparing(Student::getScore)))); map3.forEach((x,y)-> System.out.println(x+"->"+y)); /** * mapping */ Map<String,Set<Integer>> map4 = Arrays.stream(students).collect(Collectors.groupingBy(Student::getName,Collectors.mapping(Student::getScore,Collectors.toSet()))); map4.forEach((x,y)-> System.out.println(x+"->"+y)); }
8 原始類型流
在數據量比較大的情況下,將基本數據類型(int,double...)包裝成相應對象流的做法是低效的,因此,我們也可以直接將數據初始化為原始類型流,在原始類型流上的操作與對象流類似,我們只需要記住兩點
1.原始類型流的初始化
2.原始類型流與流對象的轉換
DoubleStream doubleStream; IntStream intStream; /** * 原始類型流的初始化 */ @Before public void testStream1(){ doubleStream = DoubleStream.of(0.1,0.2,0.3,0.8); intStream = IntStream.of(1,3,5,7,9); IntStream stream1 = IntStream.rangeClosed(0,100); IntStream stream2 = IntStream.range(0,100); } /** * 流與原始類型流的轉換 */ @Test public void testStream2(){ Stream<Double> stream = doubleStream.boxed(); doubleStream = stream.mapToDouble(Double::new); }
9 並行流
可以將普通順序執行的流轉變為並行流,只需要調用順序流的parallel() 方法即可,如Stream.iterate(1, x -> x + 1).limit(10).parallel()。
1) 並行流的執行順序
我們調用peek方法來瞧瞧並行流和串行流的執行順序,peek方法顧名思義,就是偷窺流內的數據,peek方法聲明為Stream<T> peek(Consumer<? super T> action);加入打印程序可以觀察到通過流內數據,見如下代碼:
public void peek1(int x) { System.out.println(Thread.currentThread().getName() + ":->peek1->" + x); } public void peek2(int x) { System.out.println(Thread.currentThread().getName() + ":->peek2->" + x); } public void peek3(int x) { System.out.println(Thread.currentThread().getName() + ":->final result->" + x); } /** * peek,監控方法 * 串行流和並行流的執行順序 */ @org.junit.Test public void testPeek() { Stream<Integer> stream = Stream.iterate(1, x -> x + 1).limit(10); stream.peek(this::peek1).filter(x -> x > 5) .peek(this::peek2).filter(x -> x < 8) .peek(this::peek3) .forEach(System.out::println); } @Test public void testPeekPal() { Stream<Integer> stream = Stream.iterate(1, x -> x + 1).limit(10).parallel(); stream.peek(this::peek1).filter(x -> x > 5) .peek(this::peek2).filter(x -> x < 8) .peek(this::peek3) .forEach(System.out::println); }
我們將stream.filter(x -> x > 5).filter(x -> x < 8).forEach(System.out::println)的過程想象成上圖的管道,我們在管道上加入的peek相當於一個閥門,透過這個閥門查看流經的數據,
(1)當我們使用順序流時,數據按照源數據的順序依次通過管道,當一個數據被filter過濾,或者經過整個管道而輸出后,第二個數據才會開始重復這一過程
(2)當我們使用並行流時,系統除了主線程外啟動了七個線程(我的電腦是4核八線程)來執行處理任務,因此執行是無序的,但同一個線程內處理的數據是按順序進行的。
2) sorted()、distinct()等對並行流的影響
sorted()、distinct()是元素相關方法,和整體的數據是有關系的,map,filter等方法和已經通過的元素是不相關的,不需要知道流里面有哪些元素 ,並行執行和sorted會不會產生沖突呢?
結論:1.並行流和排序是不沖突的,2.一個流是否是有序的,對於一些api可能會提高執行效率,對於另一些api可能會降低執行效率,3.如果想要輸出的結果是有序的,對於並行的流需要使用forEachOrdered(forEach的輸出效率更高)
我們做如下實驗:
/** * 生成一億條0-100之間的記錄 */ @Before public void init() { Random random = new Random(); list = Stream.generate(() -> random.nextInt(100)).limit(100000000).collect(toList()); } /** * tip */ @org.junit.Test public void test1() { long begin1 = System.currentTimeMillis(); list.stream().filter(x->(x > 10)).filter(x->x<80).count(); long end1 = System.currentTimeMillis(); System.out.println("串行流執行時間:" + (end1-begin1)); list.stream().parallel().filter(x->(x > 10)).filter(x->x<80).count(); long end2 = System.currentTimeMillis(); System.out.println("並行流執行時間" + (end2-end1)); long begin1_ = System.currentTimeMillis(); list.stream().filter(x->(x > 10)).filter(x->x<80).distinct().sorted().count(); long end1_ = System.currentTimeMillis(); System.out.println("串行流執行排序時間" + (end1-begin1)); list.stream().parallel().filter(x->(x > 10)).filter(x->x<80).distinct().sorted().count(); long end2_ = System.currentTimeMillis(); System.out.println("並行流執行排序時間" + (end2_-end1_));
}
執行結果如下:
參考:
https://www.cnblogs.com/andywithu/p/7404101.html