English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java flow control

Java Array

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List

Java Queue (queue)

Java Map collection

Java Set collection

Java Input Output (I/O)/O)

Java Reader/Writer

Java other topics

Java 8 Stream

Java 8 New Features

Java 8 The API adds a new abstraction called Stream, which allows you to process data in a declarative manner.

Stream provides a high-level abstraction for Java collection operations and expressions in a way that is intuitive, similar to using SQL statements to query data from a database.

The Stream API can greatly enhance the productivity of Java programmers, allowing them to write efficient, clean, and concise code.

This style treats the set of elements to be processed as a stream, which transmits through a pipeline and can be processed at the nodes of the pipeline, such as filtering, sorting, aggregation, and so on.

The element stream goes through the processing of intermediate operations (intermediate operation) in the pipeline, and finally gets the result of the previous processing through the terminal operation (terminal operation).

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

The above process can be converted to Java code as follows:

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

What is Stream?

Stream (stream) is a queue of elements from a data source and supports aggregate operations

  • Element queue Elements are specific types of objects, forming a queue. Java's Stream does not store elements but calculates them on demand.

  • Data source The source of the stream. It can be a collection, array, I/O channel, generator, etc.

  • Aggregate operations Operations similar to SQL statements, such as filter, map, reduce, find, match, sorted, etc.

Different from the previous Collection operations, Stream operations also have two basic features:

  • Pipelining: Intermediate operations always return the stream object itself. This allows multiple operations to be chained into a pipeline, similar to the stream style (fluent style). This can optimize operations, such as lazy execution and short-circuiting).

  • Internal Iteration: In the past, collection traversal was always through Iterator or For-Each in the way, explicitly iterating outside the collection, which is called external iteration. Stream provides an internal iteration method, implemented through the visitor pattern (Visitor).

to generate streams

In Java 8 In, the collection interface has two methods to generate streams:

  • stream() − To create a sequential stream for the collection.

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

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

forEach

Stream provides a new method 'forEach' to iterate over each data in the stream. The following code snippet uses forEach to output10a random number:

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

map

The map method is used to map each element to the corresponding result. The following code snippet uses map to output the square number of each element:

List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);
// Get the corresponding square number
List<Integer> squaresList = numbers.stream().map( i -> i*i).distinct().collect(Collectors.toList());

filter

The filter method is used to filter elements by setting conditions. The following code snippet uses the filter method to filter out empty strings:

List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
// Get the number of empty strings
long count = strings.stream().filter(string -> string.isEmpty()).count();

limit

The limit method is used to get a specified number of stream elements. The following code snippet uses the limit method to print out 10 data:

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

sorted

The sorted method is used to sort streams. The following code snippet uses the sorted method to sort the output 10 a random number for sorting:

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

Parallel (parallel) program

parallelStream is an alternative method for parallel stream processing. In the following example, we use parallelStream to output the number of empty strings:

List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd", "", "jkl");
// Get the number of empty strings
long count = strings.parallelStream().filter(string -> string.isEmpty()).count();

We can easily switch between sequential execution and parallel execution.

Collectors

The Collectors class implements many reduction operations, such as converting streams to collections and aggregating elements. Collectors can be used to return lists or strings:

List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
List<String> filtered = strings.stream().filter(string -If (!string.isEmpty()).collect(Collectors.toList());
 
System.out.println("Filter list: " + filtered);
String mergedString = strings.stream().filter(string -If (!string.isEmpty()).collect(Collectors.joining(", "));
System.out.println("合并字符串: " + mergedString);

Statistics

In addition, some collectors that produce statistical results are also very useful. They are mainly used on basic types such as int, double, long, etc., and they can be used to produce statistical results similar to the following.

List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);
 
IntSummaryStatistics stats = numbers.stream().mapToInt((x) -> x).summaryStatistics();
 
System.out.println("The largest number in the list: "); + stats.getMax());
System.out.println("The smallest number in the list: "); + stats.getMin());
System.out.println("Sum of all numbers: "); + stats.getSum());
System.out.println("Average: "); + stats.getAverage());

Stream complete example

Place the following code into Java8In the Tester.java 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: ");
        
      // Calculate the number of empty strings
      List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd", "", "jkl");
      System.out.println("列表: " +strings);
      long count = getCountEmptyStringUsingJava7(strings);
        
      System.out.println("The number of empty characters is: " + count);
      count = getCountLength2UsingJava7(strings);
        
      System.out.println("字符串长度为" 3 的数量为: " + count);
        
      // Delete empty strings
      List<String> filtered = deleteEmptyStringsUsingJava7(strings);
      System.out.println("筛选后的列表: " + filtered);
        
      // Delete empty strings and merge them using commas
      String mergedString = getMergedStringUsingJava7(strings, ", ");
      System.out.println("合并字符串: " + mergedString);
      List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);
        
      // Get the square numbers of the list elements
      List<Integer> squaresList = getSquares(numbers);
      System.out.println("The list of square numbers: " + squaresList);
      List<Integer> integers = Arrays.asList(1,2,13,4,15,6,17,8,19);
        
      System.out.println("列表: " +integers);
      System.out.println("The largest number in the list: "); + getMax(integers));
      System.out.println("The smallest number in the list: "); + getMin(integers));
      System.out.println("Sum of all numbers: "); + getSum(integers));
      System.out.println("Average: "); + getAverage(integers));
      System.out.println("Random number: ");
        
      // 输出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("The largest number in the list: "); + stats.getMax());
      System.out.println("The smallest number in the list: "); + stats.getMin());
      System.out.println("Sum of all numbers: "); + stats.getSum());
      System.out.println("Average: "); + stats.getAverage());
      System.out.println("Random number: ");
        
      random.ints().limit(10).sorted().forEach(System.out::println);
        
      // Parallel processing
      count = strings.parallelStream().filter(string -> string.isEmpty()).count();
      System.out.println("The number of empty strings is: "); + count);
   }
    
   private static int getCountEmptyStringUsingJava7(List<String> strings) {
      int count = 0;
        
      for (String string : strings) {
        
         if (string.isEmpty()) {
            count++;
         }
      }
      return count;
   }
    
   private static int getCountLength2UsingJava7(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();
   }
}

Execute the above script, the output is:

$ javac Java8Tester.java 
$ java Java8Tester
Using Java 7: 
List: [abc, , bc, efg, abcd, , jkl]
The number of empty characters is: 2
String length is 3 The number of: 3
Filtered list: [abc, bc, efg, abcd, jkl]
Merge strings: abc, bc, efg, abcd, jkl
Square numbers list:9, 4, 49, 25]
List:1, 2, 13, 4, 15, 6, 17, 8, 19]
The largest number in the list: 19
The smallest number in the list: 1
Sum of all numbers: 85
Average: 9
Random number: 
-393170844
-963842252
447036679
-1043163142
-881079698
221586850
-1101570113
576190039
-1045184578
1647841045
Using Java 8: 
List: [abc, , bc, efg, abcd, , jkl]
The number of empty strings is: 2
String length is 3 The number of: 3
Filtered list: [abc, bc, efg, abcd, jkl]
Merge strings: abc, bc, efg, abcd, jkl
Squares List:9, 4, 49, 25]
List:1, 2, 13, 4, 15, 6, 17, 8, 19]
The largest number in the list: 19
The smallest number in the list: 1
Sum of all numbers: 85
Average: 9.444444444444445
Random number: 
-1743813696
-1301974944
-1299484995
-779981186
136544902
555792023
1243315896
1264920849
1472077135
1706423674
The number of empty strings is: 2

Java 8 New Features