java8: Detailed explanation of stream features, so powerful

First talk about the concept of Stream and why Java introduced Stream

Stream is one of the important features introduced by JAVA8. It is a encapsulation of the data source. The data source can be processed through this encapsulated object. Stream itself is not a data storage container and has no direct relationship with the data structure.

Why introduce Stream? JAVA7 and previous versions without Stream can also process data?

Here I want to mention "functional" programming. Friends who are familiar with python and Scala may have a certain understanding of functional programming. The way of functional programming is very efficient in data processing. Java8 should be a key consideration when designing In order to support functional programming mode, Stream is only one of its features. Features such as lamda expressions and functional interfaces are also for functional programming.

How to construct a stream

1. Stream.of method
2. List object can be directly obtained to Stream; for example: stringList.stream()
3. Stream.builder().build(); method

How to use stream to efficiently process data

1. Data traversal and processing forEach method

String[] strs = {“a”, “b”, “c”, “d”};

Stream stringStream = Stream.of(strs);

stringStream.forEach(s -> System.out.println(s));

2. Data conversion map method

Functional-oriented programming generally tends to data objects are immutable, and new objects can be generated when they need to be changed. Map is to complete the mapping of objects; for example, convert lowercase letters to uppercase letters;

List upperCase = stringStream.map(s -> s.toUpperCase()).collect(Collectors.toList());

3. Data filtering filter method Insert picture description here
4. findFirst find the first element Insert picture description here
5. Stream to array

String[] upperCase = stringStream.map(s -> s.toUpperCase()).toArray(String[]::new);

6. flatMap processing

7.peek processing

Peek is also a loop traversal. The difference from forEach is that it returns the original Stream itself after traversing. forEach did not return; Insert picture description here
8. Other methods:

.count method, .skip method.limit method.sort method.max for maximum value.min for minimum value.distinct() deduplication method;

Element matching judgment: allMatch, anyMatch, and noneMatch

Stream can be converted to set or map, similar to the way of converting to List, through the toSet and toMap methods provided by Collectors

reduce method

partitioningBy method

groupingBy method

More use cases can be obtained by following and privately mailing to me.

Other features

Lazy evaluation
Supports whether to choose concurrent computing, through the .parallel() method to achieve Insert picture description here
zero-based learning Java programming, you can join my ten-year Java learning field .

Guess you like

Origin blog.csdn.net/weixin_49794051/article/details/112802400