The Java 8 API has added a new abstraction called a Stream that lets you process data in a declarative way.

Stream provides a high-level abstraction of Java collection operations and expressions in an intuitive manner similar to querying data from a database with SQL statements.

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

This style treats the collection of elements to be processed as a stream that travels through a pipe and can be processed at the nodes of the pipe, such as filtering, sorting, aggregating, and so on.

The element stream is processed by intermediate operation in the pipe, and finally the result of the previous processing is obtained by terminal operation.


What is a Stream?

A Stream is a queue of elements from a data source and supports aggregation operations

  • Elements are objects of a specific type that form a queue. A Stream in Java does not store elements, but evaluates them on demand.
  • Data source Indicates the source of the flow. These can be collections, arrays, I/O channels, generators, etc.
  • Aggregation operations are similar to SQL statements, such as filter, Map, reduce, find, match, sorted, and so on.

Unlike the previous Collection operation, the Stream operation has two basic characteristics:

  • Pipelining: All intermediate operations return the flow object itself. These operations can be cascaded into a pipe, as in fluent style. This allows you to optimize operations, such as delay and short-circuiting.
  • Internal iteration: Previously, collections were iterated explicitly outside the collection using either Iterator or for-each. This is called external iteration. A Stream provides a means of iterating internally through a Visitor pattern.

1. Create a stream

  • Stream () − Creates a serial stream for the collection.
  • ParallelStream () − Creates parallel streams for collections. ParallelStream is simply a stream that executes in parallel. It is possible to increase the speed of multi-threaded tasks through the default ForkJoinPool. Parallel streams can be disordered in traversal.
public class ParallelStream {
	public static void main(String[] args) {
		List<Integer> numbers = Arrays.asList(1.2.3.4.5.6.7.8.9); numbers.stream().forEach(System.out::print); }}Copy the code

ForEach, map, filter, limit, sorted

numbers.stream().forEach(System.out::print);  
numbers.stream().forEach(i->System.out.print(i));  
Copy the code

The two methods are equivalent.

forEach

ForEach is used to iterate over data in a stream, as in creating a stream above. ForEach shouldn’t be too hard to understand after looking at the examples in the meeting. Note that the forEach operation cannot change the traversal object itself.

Map

The map method is used to map each element to its corresponding result, most often to process data. Here is a code that increments the elements of the original list by 2:

public class MapDemo {
	public static void main(String[] args) {
		List<Integer> numbers = Arrays.asList(1.2.3.4.5.6.7.8.9);
		List<Integer> outPutList = numbers.stream().map(i -> i + 2).distinct().collect(Collectors.toList());
		outPutList.forEach(n->System.out.print(n+"")); }}Copy the code

filter

The filter method is used to filter out elements by the set criteria. 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
int count = strings.stream().filter(string -> string.isEmpty()).count();
Copy the code

Limit

The limit method is used to get a specified number of streams. The following code snippet prints 10 pieces of data using the limit method:

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

Another is commonly used in conjunction with the skip() method for paging.

int pageSize=10;
int currentPage=1;
return pageList.stream()
		.skip(pageSize * (currentPage-1))
		.limit(pageSize)
		.collect(Collectors.toList());
Copy the code

sorted

The sorted method is used to sort convection. The following code snippet uses the sorted method to sort the 10 random numbers output:

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

Collectors

Collectors can be used to return lists or strings. This example introduces a map. The following provides an example for Collectors:

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("Filter list:"+ filtered); String mergedString = strings.stream().filter(string -> ! string.isEmpty()).collect(Collectors.joining(","));
System.out.println("Merge string:" + mergedString);
Copy the code

Three, statistics

As the name implies, statistics are used to count data, usually on basic types such as int, double, and long.

List<Integer> numbers = Arrays.asList(3.2.2.3.7.3.5);
IntSummaryStatistics stats = integers.stream().mapToInt((x) -> x).summaryStatistics();

System.out.println("Maximum number in list:" + stats.getMax());
System.out.println("Smallest number in list:" + stats.getMin());
System.out.println("Sum of all numbers:" + stats.getSum());
System.out.println("Average:" + stats.getAverage());
Copy the code

The Stream code is new to the declarative programming style. The next article will probably cover lambda expressions and Optional. We’ll use more declarative programming.