Java8數據流

流/Stream是在JAVA8中引入的一個抽象,可以處理類似SQL語句聲明數據。 例如,考慮下面的SQL語句。

SELECT max(salary),employee_id,employee_name FROM Employee

上面的SQL表達式會自動返回最大薪水員工的細節,沒有對開發者的最終做任何計算。在Java中使用集合框架,開發人員必須使用循環,使檢查反覆。另一個值得關注的是效率,多核處理器可放心,Java開發人員必須編寫的並行代碼處理,但是非常容易出錯。

爲了解決這樣的問題,JAVA8引入了流的概念,它允許開發者通過聲明處理數據,並可以leverate多核架構,而不需要編寫任何特定的代碼。

什麼是數據流?

流代表從支持聚合操作源的序列的對象。以下是數據流的特點。

  • 元素序列 - 流提供了一組特定類型的以順序方式元素。流獲取/計算需求的元素。它不存儲元素。

  • 源- 流使用集合,數組或I/O資源爲輸入源。

  • 聚合操作 - 數據流支持如filter, map, limit, reduced, find, match等聚合操作。

  • 管道傳輸 - 大多數流操作的返回流本身使他們的結果可以被管道傳輸。這些操作被稱爲中間操作以及它們的功能是利用輸入,處理輸入和輸出返回到目標。collect()方法是終端操作,這是通常出現在管道傳輸操作結束標記流的結束。

  • 自動迭代 - 流操作內部做了反覆對比,其中明確迭代需要集合提供源元素。

生成數據流

使用Java8,Collection 接口有兩個方法來生成流。

  • stream() -返回順序流考慮集合作爲其源。

  • parallelStream() - 返回並行數據流考慮集合作爲其源。

List strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
List filtered = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList());

ForEach

數據流提供了新的forEach方法遍歷該流中的每個元素。考慮下面的例子打印10個隨機數字。

Random random = new Random();
random.ints().limit(10).forEach(System.out::println);

map

map方法用於映射每個元素對應的結果。考慮下面的例子打印唯一的方形數字。

List numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);
//get list of unique squares
List squaresList = numbers.stream().map( i -> i*i).distinct().collect(Collectors.toList());

filter

filter方法用於消除基於標準元素。考慮下面的例子打印空字符串計數(總數)。

Liststrings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
//get count of empty string
int count = strings.stream().filter(string -> string.isEmpty()).count();

limit

limit 方法用於減少流的大小。考慮下面的例子打印10個隨機數字。

Random random = new Random();
random.ints().limit(10).forEach(System.out::println);

sorted

sorted方法用來流排序。考慮下面的例子打印10個隨機數字的排序順序。

Random random = new Random();
random.ints().limit(10).sorted().forEach(System.out::println);

並行處理

parallelStream是流進行並行處理的替代方案。考慮下面的例子打印空字符串計數。

List strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
//get count of empty string
int count = strings.parallelStream().filter(string -> string.isEmpty()).count();

這是很容易在順序和並行的流之間進行切換。

收集器

收集器是用來處理組合在一個數據流的元素的結果。收集器可用於返回一個列表或一個字符串。

Liststrings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
List filtered = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList());
System.out.println("Filtered List: " + filtered);
String mergedString = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.joining(", "));
System.out.println("Merged String: " + mergedString);

統計

使用Java8,統計收集器引入計算所有統計數據時,流處理可以做這些。

List numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);

IntSummaryStatistics stats = integers.stream().mapToInt((x) -> x).summaryStatistics();

System.out.println("Highest number in List : " + stats.getMax());
System.out.println("Lowest number in List : " + stats.getMin());
System.out.println("Sum of all numbers : " + stats.getSum());
System.out.println("Average of all numbers : " + stats.getAverage());

Stream 例子

選擇使用任何編輯器創建以下java程序在C:/> JAVA

Java8Tester.java

import java.util.ArrayList;
import java.util.Arrays;
import java.util.IntSummaryStatistics;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;
import java.util.Map;

public class Java8Tester {
public static void main(String args[]){

  System.out.println("Using Java 7: ");
  // Count empty strings
  List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
  System.out.println("List: " +strings);
  long count = getCountEmptyStringUsingJava7(strings);        
  System.out.println("Empty Strings: " + count);

  count = getCountLength3UsingJava7(strings);        
  System.out.println("Strings of length 3: " + count);

  //Eliminate empty string
  List<String> filtered =  deleteEmptyStringsUsingJava7(strings);
  System.out.println("Filtered List: " + filtered);

  //Eliminate empty string and join using comma.
  String mergedString = getMergedStringUsingJava7(strings,", ");
  System.out.println("Merged String: " + mergedString);

  List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);

  //get list of square of distinct numbers
  List<Integer> squaresList =  getSquares(numbers);
  System.out.println("Squares List: " + squaresList);

  List<Integer> integers = Arrays.asList(1,2,13,4,15,6,17,8,19);
  System.out.println("List: " +integers);
  System.out.println("Highest number in List : " + getMax(integers));
  System.out.println("Lowest number in List : " + getMin(integers));
  System.out.println("Sum of all numbers : " + getSum(integers));
  System.out.println("Average of all numbers : " + getAverage(integers));
  System.out.println("Random Numbers: ");
  //print ten random numbers
  Random random = new Random();
  for(int i=0; i < 10; i++){
     System.out.println(random.nextInt());
  }
  System.out.println("Using Java 8: ");
  System.out.println("List: " +strings);
  count = strings.stream().filter(string->string.isEmpty()).count();
  System.out.println("Empty Strings: " + count);

  count = strings.stream().filter(string -> string.length() == 3).count();
  System.out.println("Strings of length 3: " + count);

  filtered = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList());
  System.out.println("Filtered List: " + filtered);

  mergedString = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.joining(", "));
  System.out.println("Merged String: " + mergedString);

  squaresList = numbers.stream().map( i -> i\*i).distinct().collect(Collectors.toList());
  System.out.println("Squares List: " + squaresList);       

  System.out.println("List: " +integers);
  IntSummaryStatistics stats = integers.stream().mapToInt((x) -> x).summaryStatistics();

  System.out.println("Highest number in List : " + stats.getMax());
  System.out.println("Lowest  number in List : " + stats.getMin());
  System.out.println("Sum of all numbers : " + stats.getSum());
  System.out.println("Average of all  numbers : " + stats.getAverage());
  System.out.println("Random Numbers: ");
  random.ints().limit(10).sorted().forEach(System.out::println);

  //parallel processing
  count = strings.parallelStream().filter(string -> string.isEmpty()).count();
  System.out.println("Empty Strings: " + count);

}

private static int getCountEmptyStringUsingJava7(List strings){
int count = 0;
for(String string: strings){
if(string.isEmpty()){
count++;
}
}
return count;
}
private static int getCountLength3UsingJava7(List strings){
int count = 0;
for(String string: strings){
if(string.length() == 3){
count++;
}
}
return count;
}
private static List deleteEmptyStringsUsingJava7(List strings){
List filteredList = new ArrayList();
for(String string: strings){
if(!string.isEmpty()){
filteredList.add(string);
}
}
return filteredList;
}

private static String getMergedStringUsingJava7(List strings, String seperator){
StringBuilder stringBuilder = new StringBuilder();
for(String string: strings){
if(!string.isEmpty()){
stringBuilder.append(string);
stringBuilder.append(seperator);
}
}
String mergedString = stringBuilder.toString();
return mergedString.substring(0, mergedString.length()-2);
}

private static List getSquares(List numbers){
List squaresList = new ArrayList();
for(Integer number: numbers){
Integer square = new Integer(number.intValue() * number.intValue());
if(!squaresList.contains(square)){
squaresList.add(square);
}
}
return squaresList;
}

private static int getMax(List numbers){
int max = numbers.get(0);
for(int i=1;i< numbers.size();i++){
Integer number = numbers.get(i);
if(number.intValue() > max){
max = number.intValue();
}
}
return max;
}

private static int getMin(List numbers){
int min = numbers.get(0);
for(int i=1;i< numbers.size();i++){
Integer number = numbers.get(i);
if(number.intValue() < min){
min = number.intValue();
}
}
return min;
}

private static int getSum(List numbers){
int sum = numbers.get(0);
for(int i=1;i< numbers.size();i++){
sum += numbers.get(i).intValue();
}
return sum;
}
private static int getAverage(List numbers){
return getSum(numbers) / numbers.size();
}
}

驗證結果

使用javac編譯器編譯如下類

C:\JAVA>javac Java8Tester.java

現在運行Java8Tester看到的結果

C:\JAVA>java Java8Tester

看到結果

Using Java 7:
List: [abc, , bc, efg, abcd, , jkl]
Empty Strings: 2
Strings of length 3: 3
Filtered List: [abc, bc, efg, abcd, jkl]
Merged String: abc, bc, efg, abcd, jkl
Squares List: [9, 4, 49, 25]
List: [1, 2, 13, 4, 15, 6, 17, 8, 19]
Highest number in List : 19
Lowest number in List : 1
Sum of all numbers : 85
Average of all numbers : 9
Random Numbers:
-1279735475
903418352
-1133928044
-1571118911
628530462
18407523
-881538250
-718932165
270259229
421676854
Using Java 8:
List: [abc, , bc, efg, abcd, , jkl]
Empty Strings: 2
Strings of length 3: 3
Filtered List: [abc, bc, efg, abcd, jkl]
Merged String: abc, bc, efg, abcd, jkl
Squares List: [9, 4, 49, 25]
List: [1, 2, 13, 4, 15, 6, 17, 8, 19]
Highest number in List : 19
Lowest number in List : 1
Sum of all numbers : 85
Average of all numbers : 9.444444444444445
Random Numbers:
-1009474951
-551240647
-2484714
181614550
933444268
1227850416
1579250773
1627454872
1683033687
1798939493
Empty Strings: 2