Java8新特性

Java8新特性

一、瞭解Stream

Stream是Java8中處理集合的關鍵抽象概念,它可以指定你希望對集合進行的操作,可以執行非常複雜的查詢、過濾和對映資料等操作

二、什麼是Stream

流(Stream)到底是什麼呢?是資料渠道,用於操作資料來源(集合、陣列等)所生成的元素序列。“集合講的是資料,流講的是計算!”。注意:(1)、Stream自己不會儲存元素。(2)、Stream不會改變源物件。相反,他們會返回一個持有結果的新Stream。(3)、Stream操作是延遲執行的。這意味著他們會等到需要結果的時候才執行。

三、Stream的操作三個步驟

三、Stream的操作三個步驟(1)、建立Stream一個數據源(如:集合、陣列),獲取一個流(2)、中間操作一箇中間操作鏈,對資料來源的資料進行處理(3)、終止操作(終端操作)一個終止操作,執行中間操作鏈,併產生結果。

注意:java中:>>>和>>區別

>>>表示不帶符號向右移動二進位制數,移動後前面統統補0;兩個箭頭表示帶符號移動沒有<<<這種運算子,因為左移都是補零,沒有正負數的區別。如 -12 的二進位制為:1111  1111  1111  1111  1111  1111  1111  0100;-12 >> 3 即帶符號右移3位,結果是:1111  1111  1111  1111  1111  1111  1111  1110,十進位制為: -2;-12 >>> 3 就是右移三位,前面補零,為:0001  1111  1111  1111  1111  1111  1111  1110,十進位制為:536870910。

四、建立Stream

// 可以透過Collection系列集合提供的stream()或parallelStream()List list = new ArrayList();Stream stream1 = list。stream();//透過Arrays中的靜態方法stream()獲取陣列流Employee[] emps = new Employee[10];Stream stream2 = Arrays。stream(emps);// 透過Stream類中的靜態方法of()Stream stream3 = Stream。of(“aa”, “bb”, “cc”);stream3。forEach(System。out::println);//建立無限流// 迭代Stream stream4 = Stream。iterate(0, (x) -> x + 2);stream4。limit(10)。forEach(System。out::println);// 生產Stream。generate( () -> Math。random())。limit(5)。forEach(System。out::println);

五、中間操作

5。1、篩選與切片

// 5。1。1、filter——接收 Lambda , 從流中排除某些元素。//emps。stream()。filter((e)->e。getAge() > 18) 。forEach(System。out::println);// 5。1。2、limit——截斷流,使其元素不超過給定數量。emps。stream()。filter((e)-> e。getAge()>18)。limit(2)。forEach(System。out::println);// 5。1。3、 skip(n) ——跳過元素,返回一個扔掉了前 n 個元素的流。若流中元素不足 n 個,則返回一個空流。與 limit(n) 互補emps。stream()。filter((e)->e。getAge()>18) 。skip(2)。forEach(System。out::println);// 5。1。4、distinct——篩選,透過流所生成元素的 hashCode() 和 equals() 去除重複元素emps。stream()。distinct()。forEach(System。out::println);

5。2、對映

5。2。1、map-接收Lambda,將元素轉換成其他形式或提取資訊。接收一個函式作為引數,該函式會被應用到每個元素上,並將其對映成一個新的元素。5。2。2、flatMap-接收一個函式作為引數,將流中的每個值都轉換成另一個流,然後把所有流連線成一個流 List list = Arrays。asList(“aaa”, “bbb”, “ccc”); list。stream()。map((str)->str。toUpperCase()) 。forEach(System。out::println); System。out。println(“————”); List emps = Arrays。asList( new Employee(102, “李四”, 59, 6666。66), new Employee(101, “張三”, 18, 9999。99), new Employee(103, “王五”, 28, 3333。33), new Employee(104, “趙六”, 8, 7777。77), new Employee(104, “趙六”, 8, 7777。77), new Employee(104, “趙六”, 8, 7777。77), new Employee(105, “田七”, 38, 5555。55) ); emps。stream() 。map(Employee::getName) 。forEach(System。out::println); //流中流 Stream> stream = list。stream() 。map(TestStream::filterCharacter); stream。forEach(sm->{ sm。forEach(System。out::println); }); Stream flatMap = list。stream() 。flatMap(TestStream::filterCharacter); flatMap。forEach(System。out::println);}/** * 測試map跟flatMap的區別 * 有點跟集合中的add跟addAll方法類似 * add是將無論是元素還是集合,整體加到其中一個集合中去[1,2,3。[2,3]] * addAll是將無論是元素還是集合,都是將元素加到另一個集合中去。[1,2,3,2,3] * @param str * @return */public static Stream filterCharacter(String str) { List list = new ArrayList<>(); for( Character character:str。toCharArray()){ list。add(character); } return list。stream();}

5。3、排序

5。3。1、sorted()——-自然排序(Comparable)5。3。2、sorted(Comparator com)——定製排序(Comparator)List list = Arrays。asList(“aa”, “cc”, “dd”,“ee”);list。stream()。sorted()。forEach(System。out::println);System。out。println(“=====”);List emps = Arrays。asList( new Employee(102, “李四”, 59, 6666。66), new Employee(101, “張三”, 18, 9999。99), new Employee(103, “王五”, 28, 3333。33), new Employee(104, “趙六”, 8, 7777。77), new Employee(104, “趙六”, 8, 7777。77), new Employee(104, “趙六”, 8, 7777。77), new Employee(105, “田七”, 38, 5555。55));emps。stream()。sorted((x,y)-> { if (x。getAge() == y。getAge()) { return x。getName()。compareTo(y。getName()); } else { return Integer。compare(x。getAge(), y。getAge()); }})。forEach(System。out::println);

六、終止操作

6。1、查詢與匹配

allMatch——檢查是否匹配所有元素anyMatch——檢查是否至少匹配一個元素noneMatch——檢查是否沒有匹配的元素findFirst——返回第一個元素findAny——返回當前流中的任意元素count——返回流中元素的總個數max——返回流中最大值min——返回流中最小值List emps = Arrays。asList( new Employee2(102, “李四”, 59, 6666。66, Employee2。Status。BUSY。BUSY), new Employee2(101, “張三”, 18, 9999。99, Employee2。Status。FREE), new Employee2(103, “王五”, 28, 3333。33, Employee2。Status。VOCATION), new Employee2(104, “趙六”, 8, 7777。77, Employee2。Status。BUSY), new Employee2(104, “趙六”, 8, 7777。77, Employee2。Status。FREE), new Employee2(104, “趙六”, 8, 7777。77, Employee2。Status。FREE), new Employee2(105, “田七”, 38, 5555。55, Employee2。Status。BUSY));System。out。println(“allMatch”);// allMatchboolean allMath = emps。stream()。allMatch((e)->e。getStatus()。equals(Employee2。Status。BUSY));System。out。println(allMath);System。out。println(“anyMatch”);// anyMatchboolean anyMath = emps。stream()。anyMatch((e)->e。getAge()>18);System。out。println(anyMath);System。out。println(“noneMatch”);// noneMatchboolean noneMath = emps。stream()。noneMatch((e)->e。getStatus()。equals(Employee2。Status。BUSY));System。out。println(noneMath);System。out。println(“findFirst”);// findFirstOptional findFirst = emps。stream()。sorted((e1,e2)->Double。compare(e1。getSalary(), e2。getSalary()))。findFirst();System。out。println(findFirst);// findAnySystem。out。println(“findAny”);Optional findAny = emps。stream()。filter((e)->e。getStatus()。equals(Employee2。Status。BUSY)) 。findAny();System。out。println(findAny);// countSystem。out。println(“count”);long count = emps。stream()。count();System。out。println(count);// maxSystem。out。println(“max”);// Optional max = emps。stream()。max(Employee2::getSalary)。map(Double::compare);// System。out。println(max);// minSystem。out。println(“min”);Optional min = emps。stream()。min((e1,e2)->Double。compare(e1。getSalary(), e2。getSalary()));System。out。println(min);

6。2、歸約

6。2。1、reduce(T identity, BinaryOperator) / reduce(BinaryOperator) ——可以將流中元素反覆結合起來,得到一個值。List list = Arrays。asList(1,2,3,4,5,6,7,8);Integer sum = list。stream()。reduce(0,(x,y)->x+y);System。out。println(sum);

6。3、收集

Collector介面中方法的實現決定了如何對流執行收集操作(如收集到List、Set、Map)。但是Collectors實用類提供了很多靜態方法,可以方便地建立常見收集器例項,具體方法與例項如下表:6。3。1、Collectors。toList()List emps = Arrays。asList( new Employee2(102, “李四”, 59, 6666。66, Employee2。Status。BUSY。BUSY), new Employee2(101, “張三”, 18, 9999。99, Employee2。Status。FREE), new Employee2(103, “王五”, 28, 3333。33, Employee2。Status。VOCATION), new Employee2(104, “趙六”, 8, 7777。77, Employee2。Status。BUSY), new Employee2(104, “趙六”, 8, 7777。77, Employee2。Status。FREE), new Employee2(104, “趙六”, 8, 7777。77, Employee2。Status。FREE), new Employee2(105, “田七”, 38, 5555。55, Employee2。Status。BUSY));System。out。println(“toList”);// Collectors。toList()List collect = emps。stream()。map(Employee2::getName)。collect(Collectors。toList());collect。forEach(System。out::println);System。out。println(“toSet”);// 6。3。2、Collectors。toSet()Set collect2 = emps。stream()。map(Employee2::getName) 。collect(Collectors。toSet());collect2。forEach(System。out::println);//6。3。3、Collectors。toCollection(HashSet::new)System。out。println(“toCollection”);HashSet collect3 = emps。stream()。map(Employee2::getName)。collect(Collectors。toCollection(HashSet::new));System。out。println(collect3);System。out。println(“maxBy”);//6。3。4、Collectors。maxBy()Optional collect5 = emps。stream() 。map(Employee2::getSalary)。collect(Collectors。maxBy(Double::compare));System。out。println(collect5。get());// 6。3。5、Collectors。minBy()System。out。println(“minBy”);Optional collect4 = emps。stream() 。map(Employee2::getSalary)。collect(Collectors。minBy(Double::compare));System。out。println(collect4);// 6。3。6、Collectors。summingDouble()System。out。println(“summingDouble”);Double collect6 = emps。stream()。collect(Collectors。summingDouble(Employee2::getSalary));System。out。println(collect6);// 6。3。7、Collectors。averagingDouble()System。out。println(“averagingDouble”);Double collect7 = emps。stream() 。collect(Collectors。averagingDouble((e)->e。getSalary()));System。out。println(collect7);// 6。3。8、Collectors。counting()System。out。println(“counting”);Long collect8 = emps。stream()。collect(Collectors。counting());System。out。println(collect8);// 6。3。9、Collectors。summarizingDouble()System。out。println(“summarizingDouble”);// Long collect9 = emps。stream()。collect(Collectors。summingDouble)// 6。3。10、分組Collectors。groupingBy()System。out。println(“groupingBy”);Map> collect10 = emps。stream() 。collect(Collectors。groupingBy((e)->e。getStatus()));System。out。println(collect10);// 6。3。11、多級分組Collectors。groupingBy()// 6。3。12、分割槽Collectors。partitioningBy()System。out。println(“partitioningBy”);// 6。3。13、組接字串Collectors。joining()System。out。println(“joining”);