Stream 流 API

In Java8 have two of the most important changes. The first is a Lambda expression; the other is Stream API.

Stream API (java.util.stream) the real functional programming style introduced to Java. This is by far the best complement to the Java class libraries, because Stream API Java programmers can greatly improve the productivity of programmers to write efficient, clean, simple code.

Stream processing is a key abstractions Java8 collection, you can specify that you want it to be a set of operations can be performed very complex search, filtering and mapping data and other operations. Use Stream API to manipulate the data collection, similar to using a SQL database query execution. Stream API may be used to perform operations in parallel. Briefly, Stream API provides an efficient and easy to use way of processing data.

Stream is a data channel, the sequence of elements for operation of the data source (set, arrays, etc.) generated. "Talking about the collection of data, responsible for storing data, Stream flow calculation is talking about, is responsible for processing the data!"

note:

①Stream he will not store element.

②Stream does not change the source object. Each time a new processing returns Stream holds a result.

③Stream operations are delayed execution. This means they will need to wait until the results have to be performed.

④ each Stream object can only be used once

Stream operation three steps:

1- created Stream: by a data source (such as: collection, arrays), obtaining a stream

2- intermediate operation: intermediate operation is a chain of operations, data of n times the data source process, but before the end of the operation, and does not actually executed.

3- terminating operation: Upon termination operation performed, the operation is executed intermediate chain, to produce the final result and ends Stream.

 

Creating Stream

1. Create a Stream ways: through the collection

The Java8 Collection interface is extended to provide a method of obtaining two streams:

  • public default Stream <E> stream (): returns a sequential stream

  • public default Stream <E> parallelStream (): returns a parallel stream

2. Create Stream way: through the array

Arrays of static methods stream Java8 () Gets an array of streams may be:

  • public static <T> Stream <T> stream (T [] array): Returns a stream

Overloads, capable of handling an array corresponding to the basic types:

  • public static IntStream stream (int [] array): returns an integer data stream

  • public static LongStream stream (long [] array): returns a long data stream

  • public static DoubleStream stream (double [] array): returns a floating-point data streams

3. Create Stream Three ways: through of Stream's ()

Stream class can call the static method of (), created by displaying the value of a stream. It can receive any number of parameters.

  • public static <T> Stream <T> of (T ... values): Returns a sequential stream

4. Create a Stream Four ways: Create an unlimited stream

You can use the static method Stream.iterate () and Stream.generate (), create an infinite stream.

  • public static <T> Stream <T> iterate (final T seed, final UnaryOperator <T> f): Returns an infinite stream

  • public static <T> Stream <T> generate (Supplier <T> s): Returns an infinite stream

import java.util.Arrays;
import java.util.List;
import java.util.stream.IntStream;
import java.util.stream.Stream;

import org.junit.Test;

public class Test07StreamCreate {
	@Test
	public void test06(){
		/*
		 * Stream<T> iterate(T seed, UnaryOperator<T> f)  
		 * UnaryOperator接口,SAM接口,抽象方法:
		 * 
		 * UnaryOperator<T> extends Function<T,T>
		 * 		T apply(T t)
		 */
		Stream<Integer> stream = Stream.iterate(1, num -> num+=2);
//		stream = stream.limit(10);
		stream.forEach(System.out::println);
	}
	
	@Test
	public void test05(){
		Stream<Double> stream = Stream.generate(Math::random);
		stream.forEach(System.out::println);
	}
	
	@Test
	public void test04(){
		Stream<Integer> stream = Stream.of(1,2,3,4,5);
		stream.forEach(System.out::println);
	}
	
	@Test
	public void test03(){
		String[] arr = {"hello","world"};
		Stream<String> stream = Arrays.stream(arr);
	}
	
	@Test
	public void test02(){
		int[] arr = {1,2,3,4,5};
		IntStream stream = Arrays.stream(arr);
	}
	
	@Test
	public void test01(){
		List<Integer> list = Arrays.asList(1,2,3,4,5);
		
		//JDK1.8中,Collection系列集合增加了方法
		Stream<Integer> stream = list.stream();
	}
}

 

Intermediate operation

A plurality of intermediate operations may be joined to form a pipeline, the pipeline operation unless the terminating trigger, as otherwise the operation does not perform any process! All at once and the termination processing operation, called "lazy evaluation."

method Drawing predicates
filter(Predicate p) Receiving Lambda, exclude certain elements from the stream
distinct() Screening, equals the flow generated by the elements () element deduplication
limit(long maxSize) Flow cut off, so no more than a given number of elements
skip(long n) Skip element, a return flow throw the first n elements. If the flow is less than n number of elements, an empty stream. And the limit (n) of complementary
peek(Consumer action) Receiving Lambda, each data is performed in convection operation member Lambda
sorted() Generating a new stream, wherein the natural order sort
sorted(Comparator com) Generating a new flow, wherein the comparator sorted order
map(Function f) Receiving a function as a parameter, the function will be applied to each element, and maps it into a new element.
mapToDouble(ToDoubleFunction f) Receiving a function as a parameter, the function will be applied to each element, to produce a new DoubleStream.
mapToInt(ToIntFunction f) Receiving a function as a parameter, the function will be applied to each element, to produce a new IntStream.
mapToLong (ToLongFunction f) Receiving a function as a parameter, the function will be applied to each element, to produce a new LongStream.
flatMap(Function f) Receiving a function as a parameter, the value of each stream are replaced with another stream, then all flows connected into one stream

 

mport java.util.Arrays;
import java.util.stream.Stream;

import org.junit.Test;

public class Test08StreamMiddle {
	
	@Test
	public void test12(){
		String[] arr = {"hello","world","java"};
		Arrays.stream(arr)
			.flatMap(t -> Stream.of(t.split("|")))//Function<T,R>接口抽象方法 R apply(T t)  现在的R是一个Stream
			.forEach(System.out::println);
	}
	
	
	@Test
	public void test11(){
		String[] arr = {"hello","world","java"};
		
		Arrays.stream(arr)
			.map(t->t.toUpperCase())
			.forEach(System.out::println);
	}
	
	@Test
	public void test10(){
		Stream.of(1,2,3,4,5)
			.map(t -> t+=1)//Function<T,R>接口抽象方法 R apply(T t)
			.forEach(System.out::println);
	}
	
	@Test
	public void test09(){
		//希望能够找出前三个最大值,前三名最大的,不重复
		Stream.of(11,2,39,4,54,6,2,22,3,3,4,54,54)
			.distinct()
			.sorted((t1,t2) -> -Integer.compare(t1, t2))//Comparator接口  int compare(T t1, T t2)
			.limit(3)
			.forEach(System.out::println);
	}
	
	@Test
	public void test08(){
		long count = Stream.of(1,2,3,4,5,6,2,2,3,3,4,4,5)
			.distinct()
			.peek(System.out::println)  //Consumer接口的抽象方法  void accept(T t)
			.count();
		System.out.println("count="+count);
	}
	
	
	@Test
	public void test07(){
		Stream.of(1,2,3,4,5,6,2,2,3,3,4,4,5)
			.skip(5)
			.distinct()
			.filter(t -> t%3==0)
			.forEach(System.out::println);
	}

	@Test
	public void test06(){
		Stream.of(1,2,3,4,5,6,2,2,3,3,4,4,5)
			.skip(5)
			.forEach(System.out::println);
	}
	
	@Test
	public void test05(){
		Stream.of(1,2,2,3,3,4,4,5,2,3,4,5,6,7)
			.distinct()  //(1,2,3,4,5,6,7)
			.filter(t -> t%2!=0) //(1,3,5,7)
			.limit(3)
			.forEach(System.out::println);
	}
	
	
	@Test
	public void test04(){
		Stream.of(1,2,3,4,5,6,2,2,3,3,4,4,5)
			.limit(3)
			.forEach(System.out::println);
	}
	
	
	@Test
	public void test03(){
		Stream.of(1,2,3,4,5,6,2,2,3,3,4,4,5)
			.distinct()
			.forEach(System.out::println);
	}
	
	
	@Test
	public void test02(){
		Stream.of(1,2,3,4,5,6)
			.filter(t -> t%2==0)
			.forEach(System.out::println);
	}
	
	@Test
	public void test01(){
		//1、创建Stream
		Stream<Integer> stream = Stream.of(1,2,3,4,5,6);
		
		//2、加工处理
		//过滤:filter(Predicate p)
		//把里面的偶数拿出来
		/*
		 * filter(Predicate p)
		 * Predicate是函数式接口,抽象方法:boolean test(T t)
		 */
		stream = stream.filter(t -> t%2==0);
		
		//3、终结操作:例如:遍历
		stream.forEach(System.out::println);
	}
}

End of Operation

The terminal will generate results from the pipeline flow. The result can be any value is not a stream, for example: List, Integer, or even void. After termination of the operation flow, not be used again.

method description
boolean allMatch(Predicate p) Check that all the elements match
boolean anyMatch(Predicate p) Check the matches at least one element
boolean noneMatch(Predicate p) Check if there is no match for all elements
Optional<T> findFirst() Returns the first element
Optional<T> findAny() Return any element in the current flow
long count() Returns the total number of elements in stream
Optional<T> max(Comparator c) Returns the maximum flow
Optional<T> min(Comparator c) Returns the minimum flow
void forEach(Consumer c) Iteration
T reduce(T iden, BinaryOperator b) Stream may be repeated to combine elements, obtain a value. Return T
U reduce(BinaryOperator b) Stream may be repeated to combine elements, obtain a value. Back Optional <T>
R collect(Collector c) The stream is converted to other forms. Collector receiving interface to implement a process to make elements Stream Summary for

Collector implement the interface method determines the action to perform how convection collected (such as collecting the List, Set, Map). In addition, Collectors utility class provides many static methods, you can easily create a common collector instance.

public class Test09StreamEnding {
	
	@Test
	public void test14(){
		List<Integer> list = Stream.of(1,2,4,5,7,8)
				.filter(t -> t%2==0)
				.collect(Collectors.toList());
		
		System.out.println(list);
	}
	
	
	@Test
	public void test13(){
		Optional<Integer> max = Stream.of(1,2,4,5,7,8)
			 .reduce((t1,t2) -> t1>t2?t1:t2);//BinaryOperator接口   T apply(T t1, T t2)
		System.out.println(max);
	}
	
	@Test
	public void test12(){
		Integer reduce = Stream.of(1,2,4,5,7,8)
			 .reduce(0, (t1,t2) -> t1+t2);//BinaryOperator接口   T apply(T t1, T t2)
		System.out.println(reduce);
	}
	
	@Test
	public void test11(){
		Optional<Integer> max = Stream.of(1,2,4,5,7,8)
				.max((t1,t2) -> Integer.compare(t1, t2));
		System.out.println(max);
	}
	
	@Test
	public void test10(){
		Optional<Integer> opt = Stream.of(1,2,4,5,7,8)
				.filter(t -> t%3==0)
				.findFirst();
		System.out.println(opt);
	}
	
	@Test
	public void test09(){
		Optional<Integer> opt = Stream.of(1,2,3,4,5,7,9)
				.filter(t -> t%3==0)
				.findFirst();
		System.out.println(opt);
	}
	
	@Test
	public void test08(){
		Optional<Integer> opt = Stream.of(1,3,5,7,9).findFirst();
		System.out.println(opt);
	}
	
	@Test
	public void test04(){
		boolean result = Stream.of(1,3,5,7,9)
			.anyMatch(t -> t%2==0);
		System.out.println(result);
	}
	
	
	@Test
	public void test03(){
		boolean result = Stream.of(1,3,5,7,9)
			.allMatch(t -> t%2!=0);
		System.out.println(result);
	}
	
	@Test
	public void test02(){
		long count = Stream.of(1,2,3,4,5)
				.count();
		System.out.println("count = " + count);
	}
	
	@Test
	public void test01(){
		Stream.of(1,2,3,4,5)
				.forEach(System.out::println);
	}
}

 

Published 126 original articles · won praise 6 · views 3691

Guess you like

Origin blog.csdn.net/qq_40244391/article/details/104435754