Five new features of jdk8 Stream API

Posted by phpnewbiy on Wed, 08 Apr 2020 09:26:34 +0200

Introduction

The Java 8 API adds a new abstraction called streaming Stream, which allows you to process data in a declarative way. Stream provides a high-level abstraction of Java set operations and expressions in an intuitive way similar to querying data from a database using SQL statements. Stream API can greatly improve the productivity of Java programmers and make them write efficient, clean and concise code. This style regards the set of elements to be processed as a flow, which is transmitted in the pipeline and can be processed on the nodes of the pipeline, such as filtering, sorting, aggregation, etc. The element flow is processed by intermediate operation in the pipeline, and the final operation gets the result of the previous processing.

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

####What's new in java8

  1. Lambda expression, one of the new features of jdk8
  2. Method reference of the second new feature of jdk8
  3. Three function interface of new characteristics of jdk8
  4. Four default methods for new features of jdk8
  5. Five new features of jdk8 Stream API
  6. Six Optional classes of new features of jdk8
  7. Seven new features of jdk8 Nashorn JavaScript
  8. New features of jdk8 date time API
  9. Nine new features of jdk8 Base64

What is Stream?

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

  • The element is a specific type of object, forming a queue. Stream s in java do not store elements, but are computed on demand.
  • Data due to the source of the stream. It can be set, array, I/O channel, generator, etc.
  • Aggregation operations are similar to SQL statements, such as filter,map.reduce.find,match,sorted, etc. Unlike previous Collection operations, Stream operations have two basic features:
  • Pipelining: intermediate operations return the flow object itself. In this way, multiple operations can be connected in series into a pipe, just like the fluent style. Doing so optimizes operations such as lazy execution and short circuiting.
  • Internal iteration: in the past, iterator or for each was used to iterate the set explicitly outside the set, which is called external iteration. Stream provides an internal iteration method, which is implemented by visitor mode.

Generating stream

There are two ways to generate a flow: stream() - creates a serial stream for the collection. parallelStream() - creates a parallel stream for the collection.

List<String> list=Arrays.asList("a","b","c","d","e","f","g");
//Create a serial stream
Stream<String> stream=list.stream();
//Create parallel flow
Stream<String> stream2=list.parallelStream();
//The difference between serial flow and parallel flow: a simple understanding of parallel flow is an implementation of multithreaded asynchronous tasks.
//Let's take a look at the specific example, serial stream and parallel stream printout effect:
System.out.print("Serial stream:");
stream.forEach(str-> System.out.print(str));
System.out.println("");
System.out.print("Parallel flow:");
stream2.forEach(str-> System.out.print(str));

The operation output is:

Serial stream: abcdefg
 Parallel flow: edgfbac

We find that when we use parallel stream, the result is not output in the original order of the collection. To further prove that the operation is parallel, we print out the thread information.

stream2.forEach(str-> System.out.println(Thread.currentThread().getName()+"->"+str));

The operation output is:

main->e
ForkJoinPool.commonPool-worker-1->b
ForkJoinPool.commonPool-worker-2->g
ForkJoinPool.commonPool-worker-1->c
main->d
ForkJoinPool.commonPool-worker-2->f
ForkJoinPool.commonPool-worker-3->a

Through the example, we can be sure that the parallel stream is implemented by multithreading, which can greatly simplify our use of concurrent operations.

forEach

Stream provides a new method for each to iterate over each data in the stream.

//Output 10 random numbers with foreach
Random random=new Random();
System.out.println("Random 10 numbers:");
random.ints(10).forEach(System.out::println);

map

The map method is used to map each element to the result of for.

//map snippet
List<Integer> muns=Arrays.asList(1,2,3,4,5,6,7,8,9);
//Set element median * 2
muns=muns.stream().map(n-> n*2).collect(Collectors.toList());
System.out.println("Use map Results after treatment:");
muns.stream().forEach(n->System.out.println(n));

filter

The filter method is used to filter out elements through the set conditions.

List<Integer> muns=Arrays.asList(1,2,3,4,5,6,7,8,9);
System.out.println("Use filter Results after treatment:");
//If the filter element is greater than 5, the output number is 6-9
muns.stream().filter(n -> n>5).forEach(n->System.out.println(n));

limit

The limit method is used to get a specified number of flows

List<Integer> muns=Arrays.asList(1,2,3,4,5,6,7,8,9);
System.out.println("Use limit Results after treatment:");
///Get top 5 data
muns.stream().limit(5).forEach(n->System.out.println(n));

sorted

The sorted method is used for natural sorting of convection.

List<Integer> muns2=Arrays.asList(1,3,5,4,10,6,2,8,7);
System.out.println("Use sorted Ascending elements:");
//Sort in natural order
muns2.stream().sorted().forEach(System.out::println);
System.out.println("Use sorted Reverse elements:");		muns2.stream().sorted(Comparator.reverseOrder()).forEach(System.out::println);

You can also sort an attribute of an object in a collection:

//Create entity and assign age
TestVo vo1=new TestVo();
vo1.setAge(18);
	
TestVo vo2=new TestVo();
vo2.setAge(15);
		
TestVo vo3=new TestVo();
vo3.setAge(20);
		
List<TestVo> voList=Arrays.asList(vo1,vo2,vo3);
System.out.println("In ascending order of age:");
//Ascending age
voList.stream().sorted(Comparator.comparing(TestVo :: getAge)).forEach(v-> System.out.println(v.getAge()));
System.out.println("Age in descending order:");
//Descending age
voList.stream().sorted(Comparator.comparing(TestVo :: getAge).reversed()).forEach(v-> System.out.println(v.getAge()));

Collectors

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

List<String> list3=Arrays.asList("now","store","list","","e","f","g");
//Empty filter the collection and return it
List<String> filtered=list3.stream().filter(str -> !str.isEmpty()).collect(Collectors.toList());
System.out.println("Filter list: " + filtered);
String strarray=list3.stream().filter(str ->! str.isEmpty()).collect(Collectors.joining(","));
System.out.println("Merge strings: " + strarray);

Statistics

Some collectors that produce statistics are also useful. They are mainly used for int, double, long and other basic types. They 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=numbers.stream().mapToInt(x -> x).summaryStatistics();
System.out.println("Maximum number in list:"+stats.getMax());
System.out.println("Minimum number in list:"+stats.getMin());
System.out.println("Sum of all numbers : " + stats.getSum());
System.out.println("Average : " + stats.getAverage());

Stream full instance

package com.adanblog.demo;

import java.util.Arrays;
import java.util.Comparator;
import java.util.IntSummaryStatistics;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;
import java.util.stream.Stream;import org.omg.Messaging.SyncScopeHelper;

/**
 * java8 New feature 5 Stream
 * @author www.adanblog.com
 *
 */
public class StreamTest {
	public static void main(String[] args) {
		List<String> list=Arrays.asList("a","b","c","d","e","f","g");
		//Create a serial stream
		Stream<String> stream=list.stream();
		//Create parallel flow
		Stream<String> stream2=list.parallelStream();
		//The difference between serial flow and parallel flow: a simple understanding of parallel flow is an implementation of multithreaded asynchronous tasks.
		//Let's take a look at the specific example, serial stream and parallel stream printout effect:
		System.out.print("Serial stream:");
		stream.forEach(str-> System.out.print(str));
		System.out.println("");
		System.out.print("Parallel flow:");
		stream2.forEach(str-> System.out.print(str));
		//Verify parallel flow
		//stream2.forEach(str-> System.out.println(Thread.currentThread().getName()+"->"+str));
		System.out.println("");
		
		//Output 10 random numbers with foreach
		Random random=new Random();
		System.out.println("Random 10 numbers:");
		random.ints(10).forEach(System.out::println);
		
		
		//map snippet
		List<Integer> muns=Arrays.asList(1,2,3,4,5,6,7,8,9);
		//Set element median * 2
		muns=muns.stream().map(n-> n*2).collect(Collectors.toList());
		System.out.println("Use map Results after treatment:");
		muns.stream().forEach(n->System.out.println(n));
		
		System.out.println("Use filter Results after treatment:");
		//Filter numbers with elements greater than 5
		muns.stream().filter(n->n>5).forEach(n->System.out.println(n));
		
		System.out.println("Use limit Results after treatment:");
		///Get top 5 data
		muns.stream().limit(5).forEach(n->System.out.println(n));
		
		System.out.println("Use sorted Ascending elements:");
		List<Integer> muns2=Arrays.asList(1,3,5,4,10,6,2,8,7);
		//Sort in natural order
		muns2.stream().sorted().forEach(System.out::println);
		System.out.println("Use sorted Reverse elements:");
		muns2.stream().sorted(Comparator.reverseOrder()).forEach(System.out::println);
	
		//Create entity and assign age
		TestVo vo1=new TestVo();
		vo1.setAge(18);
	
		TestVo vo2=new TestVo();
		vo2.setAge(15);
		
		TestVo vo3=new TestVo();
		vo3.setAge(20);
		
		List<TestVo> voList=Arrays.asList(vo1,vo2,vo3);
		System.out.println("In ascending order of age:");
		//Ascending age
		voList.stream().sorted(Comparator.comparing(TestVo :: getAge)).forEach(v-> System.out.println(v.getAge()));
		System.out.println("Age in descending order:");
		//Descending age
		voList.stream().sorted(Comparator.comparing(TestVo :: getAge).reversed()).forEach(v-> System.out.println(v.getAge()));
	
		List<String> list3=Arrays.asList("now","store","list","","e","f","g");
		//Empty filter the collection and return it
		List<String> filtered=list3.stream().filter(str -> !str.isEmpty()).collect(Collectors.toList());
		System.out.println("Filter list: " + filtered);
		String strarray=list3.stream().filter(str ->! str.isEmpty()).collect(Collectors.joining(","));
		System.out.println("Merge strings: " + strarray);
		
		List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);
		IntSummaryStatistics stats=numbers.stream().mapToInt(x -> x).summaryStatistics();
		System.out.println("Maximum number in list:"+stats.getMax());
		System.out.println("Minimum number in list:"+stats.getMin());
		System.out.println("Sum of all numbers : " + stats.getSum());
		System.out.println("Average : " + stats.getAverage());
	}
}

About Adan blog

The above content is just one family's opinion. Due to limited personal ability, there are inevitably omissions and mistakes. If you find a bug or have better suggestions, you are welcome to comment and correct. Thank you very much. Here's Adan's personal blog, which records all the blogs in study and work. Welcome to visit.

Personal blog: http://www.adanblog.com/

GitHub: https://github.com/adanblog/

Topics: Programming Java SQL github Database