Latest web development tutorials

Java 8 Stream

Java 8 new features Java 8 new features


Java 8 API adds a new abstraction called stream Stream, allows you to process the data in a declarative way.

Stream uses a similar SQL statements to query data from a database in an intuitive way to provide a higher level of abstraction and expression of Java set operations.

Stream API can greatly provide Java programmer productivity, allowing programmers to write efficient, clean, simple code.

This style element to be treated as a kind of collection of stream flow in the pipeline transmission, and can be processed on the node of the pipeline, such as filtering, sorting, polymerization.

Elements flow in the pipeline through an intermediate operations (intermediate operation) processing, and finally get the results of previously processed by the final operation (terminal operation).

+--------------------+       +------+   +------+   +---+   +-------+
| stream of elements +-----> |filter+-> |sorted+-> |map+-> |collect|
+--------------------+       +------+   +------+   +---+   +-------+

The above processes into Java code:

List<Integer> transactionsIds = 
widgets.stream()
             .filter(b -> b.getColor() == RED)
             .sorted((x,y) -> x.getWeight() - y.getWeight())
             .mapToInt(Widget::getWeight)
             .sum();

What is a Stream?

Element queue Stream (stream) is a support from the data source and aggregate operations

  • Elements are specific types of objects, forming a queue. In Java Stream does not store elements, but on-demand computing.
  • Source data flow source. Can be set, arrays, I / O channel, generator and other generators.
  • Polymerization is similar to SQL statements of operations, such as filter, map, reduce, find, match, sorted and so on.

Previous Collection operate different, Stream operation there are two basic features:

  • Pipelining: intermediate operation will return a stream object itself. So that multiple operations can be concatenated into a single pipeline, style as stream (fluent style). This operation can be optimized, such as delay in execution (laziness) and short-circuit (short-circuiting).
  • Internal iteration: before collection traversal through Iterator or For-Each way, explicit external collection iterate, this is called external iteration. Stream provides an internal iterative way through the visitor pattern (Visitor) implementation.

Flow generation

In Java 8, the set interface has two methods to generate the stream:

  • stream () - create a serial stream for the collection.

  • parallelStream () - create a parallel stream for the collection.

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

forEach

Stream provides a new method of 'forEach' to iterate through each data stream. The following code fragment uses forEach output of 10 random numbers:

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

map

map method for mapping each element corresponding to the result, the following code fragment uses the output of the map corresponding to the number of square elements:

List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);
// 获取对应的平方数
List<Integer> squaresList = numbers.stream().map( i -> i*i).distinct().collect(Collectors.toList());

filter

filter method is used to set the conditions by filtering out elements. The following code fragment uses filter method filter out the empty string:

List<String>strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
// 获取空字符串的数量
int count = strings.stream().filter(string -> string.isEmpty()).count();

limit

limit method for acquiring a specified number of streams. The following code fragment uses limit method to print out the 10 data:

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

sorted

A method for convection sorted order. The following code fragment uses sorted Methods 10 random numbers output sort:

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

Parallel (parallel) program

parallelStream is parallel stream handler substitute. We use the following example to output an empty string parallelStream number:

List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
// 获取空字符串的数量
int count = strings.parallelStream().filter(string -> string.isEmpty()).count();

We can easily switch in order to run in parallel and direct.


Collectors

Collectors class implements a number of reduction operations, for example, will stream into the collection and aggregation of elements. Collectors can be used to return a list or string:

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

System.out.println("筛选列表: " + filtered);
String mergedString = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.joining(", "));
System.out.println("合并字符串: " + mergedString);

statistics

In addition, some produce statistics collector also very useful. They are mainly used for basic type int, double, long, etc., which can be used to generate statistical results similar to the following.

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

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

System.out.println("列表中最大的数 : " + stats.getMax());
System.out.println("列表中最小的数 : " + stats.getMin());
System.out.println("所有数之和 : " + stats.getSum());
System.out.println("平均数 : " + stats.getAverage());

Stream full instance

Java8Tester.java the following code into the file:

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("使用 Java 7: ");
		
      // 计算空字符串
      List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
      System.out.println("列表: " +strings);
      long count = getCountEmptyStringUsingJava7(strings);
		
      System.out.println("空字符数量为: " + count);
      count = getCountLength3UsingJava7(strings);
		
      System.out.println("字符串长度为 3 的数量为: " + count);
		
      // 删除空字符串
      List<String> filtered = deleteEmptyStringsUsingJava7(strings);
      System.out.println("筛选后的列表: " + filtered);
		
      // 删除空字符串,并使用逗号把它们合并起来
      String mergedString = getMergedStringUsingJava7(strings,", ");
      System.out.println("合并字符串: " + mergedString);
      List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);
		
      // 获取列表元素平方数
      List<Integer> squaresList = getSquares(numbers);
      System.out.println("平方数列表: " + squaresList);
      List<Integer> integers = Arrays.asList(1,2,13,4,15,6,17,8,19);
		
      System.out.println("列表: " +integers);
      System.out.println("列表中最大的数 : " + getMax(integers));
      System.out.println("列表中最小的数 : " + getMin(integers));
      System.out.println("所有数之和 : " + getSum(integers));
      System.out.println("平均数 : " + getAverage(integers));
      System.out.println("随机数: ");
		
      // 输出10个随机数
      Random random = new Random();
		
      for(int i=0; i < 10; i++){
         System.out.println(random.nextInt());
      }
		
      System.out.println("使用 Java 8: ");
      System.out.println("列表: " +strings);
		
      count = strings.stream().filter(string->string.isEmpty()).count();
      System.out.println("空字符串数量为: " + count);
		
      count = strings.stream().filter(string -> string.length() == 3).count();
      System.out.println("字符串长度为 3 的数量为: " + count);
		
      filtered = strings.stream().filter(string ->!string.isEmpty()).collect(Collectors.toList());
      System.out.println("筛选后的列表: " + filtered);
		
      mergedString = strings.stream().filter(string ->!string.isEmpty()).collect(Collectors.joining(", "));
      System.out.println("合并字符串: " + mergedString);
		
      squaresList = numbers.stream().map( i ->i*i).distinct().collect(Collectors.toList());
      System.out.println("Squares List: " + squaresList);
      System.out.println("列表: " +integers);
		
      IntSummaryStatistics stats = integers.stream().mapToInt((x) ->x).summaryStatistics();
		
      System.out.println("列表中最大的数 : " + stats.getMax());
      System.out.println("列表中最小的数 : " + stats.getMin());
      System.out.println("所有数之和 : " + stats.getSum());
      System.out.println("平均数 : " + stats.getAverage());
      System.out.println("随机数: ");
		
      random.ints().limit(10).sorted().forEach(System.out::println);
		
      // 并行处理
      count = strings.parallelStream().filter(string -> string.isEmpty()).count();
      System.out.println("空字符串的数量为: " + count);
   }
	
   private static int getCountEmptyStringUsingJava7(List<String> strings){
      int count = 0;
		
      for(String string: strings){
		
         if(string.isEmpty()){
            count++;
         }
      }
      return count;
   }
	
   private static int getCountLength3UsingJava7(List<String> strings){
      int count = 0;
		
      for(String string: strings){
		
         if(string.length() == 3){
            count++;
         }
      }
      return count;
   }
	
   private static List<String> deleteEmptyStringsUsingJava7(List<String> strings){
      List<String> filteredList = new ArrayList<String>();
		
      for(String string: strings){
		
         if(!string.isEmpty()){
             filteredList.add(string);
         }
      }
      return filteredList;
   }
	
   private static String getMergedStringUsingJava7(List<String> strings, String separator){
      StringBuilder stringBuilder = new StringBuilder();
		
      for(String string: strings){
		
         if(!string.isEmpty()){
            stringBuilder.append(string);
            stringBuilder.append(separator);
         }
      }
      String mergedString = stringBuilder.toString();
      return mergedString.substring(0, mergedString.length()-2);
   }
	
   private static List<Integer> getSquares(List<Integer> numbers){
      List<Integer> squaresList = new ArrayList<Integer>();
		
      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<Integer> 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<Integer> 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 = (int)(numbers.get(0));
		
      for(int i=1;i < numbers.size();i++){
         sum += (int)numbers.get(i);
      }
      return sum;
   }
	
   private static int getAverage(List<Integer> numbers){
      return getSum(numbers) / numbers.size();
   }
}

Implementation of the above script, output is:

$ javac Java8Tester.java 
$ java Java8Tester
使用 Java 7: 
列表: [abc, , bc, efg, abcd, , jkl]
空字符数量为: 2
字符串长度为 3 的数量为: 3
筛选后的列表: [abc, bc, efg, abcd, jkl]
合并字符串: abc, bc, efg, abcd, jkl
平方数列表: [9, 4, 49, 25]
列表: [1, 2, 13, 4, 15, 6, 17, 8, 19]
列表中最大的数 : 19
列表中最小的数 : 1
所有数之和 : 85
平均数 : 9
随机数: 
-393170844
-963842252
447036679
-1043163142
-881079698
221586850
-1101570113
576190039
-1045184578
1647841045
使用 Java 8: 
列表: [abc, , bc, efg, abcd, , jkl]
空字符串数量为: 2
字符串长度为 3 的数量为: 3
筛选后的列表: [abc, bc, efg, abcd, jkl]
合并字符串: abc, bc, efg, abcd, jkl
Squares List: [9, 4, 49, 25]
列表: [1, 2, 13, 4, 15, 6, 17, 8, 19]
列表中最大的数 : 19
列表中最小的数 : 1
所有数之和 : 85
平均数 : 9.444444444444445
随机数: 
-1743813696
-1301974944
-1299484995
-779981186
136544902
555792023
1243315896
1264920849
1472077135
1706423674
空字符串的数量为: 2

Java 8 new features Java 8 new features