JAVA JDK8 new concept Stream flow and operating a collection case

Introduced in Jdk1.8 the concept of stream flow, this "flow" is different from the IO and the input and output streams, it is a class Jdk in: java.util.stream.Stream, using the stream processing can help us enhance the performance of the code.

1. Common Applications

Stream stream using a set of filters and traverse operations:

import java.util.ArrayList;
import java.util.List;
public class Demo{
	public static void main(String[]args){
		List<String> list =new ArrayList<>();
		list.add("张三");
		list.add("李四");
		list.add("王五五");
		list.add("张强");
		list.add("张无忌");
		list.stream()
			//只要以"张"开头的
			.filter(s‐>s.startsWith("张"))
			//只要长度为3的
			.filter(s‐>s.length()==3)//forEach中传入Consumer接口的实现类,使用Lambda表达式的方法引用写法
			.forEach(System.out::println);
	}
}

2. The flow of acquisition

2.1 Stream.of()

java.util.stream.Stream<T>It is the most common stream interface Java8 new entrants. (This is not a function interface)
obtaining a stream of very simple, there are several common methods:
All Collection can set the default method acquisition stream by stream;
Streamstatic interface methods ofcan obtain an array of the corresponding stream.

//获取数组的流
int[] array = new int[10];
Stream<int[]> arrayStream = Stream.of(array);

//获取List的流,当然,对于集合的流有更简单的获取方式
List<String> list = new ArrayList<>();
Stream<List<String>> listStream = Stream.of(list);

2.2 XXX.stream()

Collection obtain flow

java.util.Collection added a default interface method used to obtain the flow stream, so that all classes can be realized acquisition stream.

public static void main(String[]args){
	List<String> list = new ArrayList<>();
	//...
	Stream<String> stream1 = list.stream();
	Set<String> set = new HashSet<>();
	//...
	Stream<String> stream2 = set.stream();
	Vector<String> vector=new Vector<>();
	//...
	Stream<String> stream3 = vector.stream();
}

Map obtain flow

Collection java.util.Map interface is not sub-interface, data structures and which does not conform KV single feature stream elements, it needs to obtain a corresponding flow fraction key, value, or the like where entry:

public static void main(String[]args) {
	Map<String,String> map = new HashMap<>();
	//...
	Stream<String> keyStream = map.keySet().stream();
	Stream<String> valueStream = map.values().stream();
	Stream<Map.Entry<String,String>> entryStream = map.entrySet().stream();
}

3. The conventional method of flow

Many methods of operation flow model, here are some common. These methods may be divided into two:

  • Delayed method: return type is still the Stream interfaces own type of method, therefore supports chained calls. (In addition to the end of the method, the other methods are delaying.)
  • End of method: the return value type is no longer Stream interface itself is the type of approach can no longer be chained calls.

3.1 forEach

void forEach(Consumer<?superT> action);
The method receives a Consumer interface function, each stream will function element to the process.
The method can override accep consumption Consumer interface implements logical way to achieve a class, more directly in a simple manner using a Lambda expression:

public static void main(String[]args){
	Stream<String> stream = Stream.of("aaa","bbb","ccc");
	stream.forEach(name ‐> System.out.println(name));
}

The method may also be utilized to further simplify reference Lambda expressions

stream.forEach(System.out :: println);

Analytical reference methods to simplify rules see separate blog:
Links: JAVA the Lambda expressions using a reference method optimization .

3.2 filter

Stream<T> filter(Predicate<?superT> predicate);

The interface receives a Predicate interface function, can implement the interface and override the test filter logic implemented method. test()The method will generate a boolean result, on behalf of the specified conditions are met. If the result is true, then the method Stream flow filter elements will be retained; if the result is false, then the filter element method will be discarded.
Of course, simple wording or the use of Lambda:

public static void main(String[]args){
	Stream<String> original = Stream.of("张三","张四","王五");
	Stream<String> result = original.filter(s->s.startsWith("张"));
}

3.3 map

The method of map element may be mapped to the stream in another stream.

<R>Stream<R> map(Function<? super T, ? extends R> mapper);

Function The interface requires a functional interface parameters, type T can convert the current data stream to another stream R type. The interface may be implemented to achieve a method and apply override mapping logic.

Of course, simple wording or the use of Lambda:

public static void main(String[]args){
	Stream<String> original = Stream.of("10","12","18");
	Stream<Integer> result = original.map(str‐>Integer.parseInt(str));
}

3.4 count

Provides a method to obtain flow count the number of elements therein.

long count();
Direct access:

public static void main(String[]args){
	Stream<String> original = Stream.of("10","12","18");
    long n = original.count();
}

3.4 limit

Streams limit method to get the first few elements.

Stream<T> limit(long maxSize);
Is a long type parameter, if the length is greater than the current set of parameters it is truncated; otherwise, no operation is performed. Basic use:

public static void main(String[]args){
	Stream<String> original = Stream.of("10","12","18");
    Stream<String> limit = original.limit(2);
    System.out.println(limit.count());//结果:2
}

Skip the first few 3.5 skip-

Stream<T> skip(long n);

If the flow is greater than the current length of n, n a skip before; otherwise 0 will be a length of blank flow. Basic use:

public static void main(String[]args){
	Stream<String> original = Stream.of("10","12","18");
    Stream<String> limit = original.skip(2);
    System.out.println(limit.count());//结果:1
}

3.6 concat- combined stream

static<T> Stream<T> concat(Stream<? extends T> a, Stream<? extends T> b)

The basic method of using the following codes:

import java.util.stream.Stream;
public class Demo{
	public static void main(String[]args){
		Stream<String> streamA = Stream.of("AAA");
		Stream<String> streamB = Stream.of("BBB");
		Stream<String> result = Stream.concat(streamA, streamB);
	}
}
Published 16 original articles · won praise 6 · views 796

Guess you like

Origin blog.csdn.net/weixin_43838446/article/details/104951456