(1) Stream overview:
1. What is Stream?
- API for simplified collection and array operations. Combined with Lambda expressions.
- A means to facilitate the operation of collections/arrays (collections/arrays are the purpose of development).
2. Experience the role of Stream:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* 体验stream流作用
*/
public class StreamDemo01 {
public static void main(String[] args) {
//需求:找到名字是小开头的,且长度为3的元素
List<String> names = new ArrayList<>();
Collections.addAll(names,"小小","小心心","小星星","大大");
System.out.println(names);
//1.遍历查找:
//1.1从集合中找出小开头的元素放到新集合
List<String> xiaoList = new ArrayList<>();
for (String name : names) {
if (name.startsWith("小")){
xiaoList.add(name);
}
}
//1.2从小开头的名字集合中找到长度为3的元素放到新集合
List<String> xiaoThreeList = new ArrayList<>();
for (String s : xiaoList) {
if (s.length() == 3){
xiaoThreeList.add(s);
}
}
System.out.println(xiaoThreeList);
//2.使用stream流方法 filter:进行过滤 forEach:对每个元素进行输出
names.stream().filter(s -> s.startsWith("小")).filter(s -> s.length() == 3).forEach(s -> System.out.println(s));
}
}
3. Stream thinking:
- First get the Stream stream of the collection or array. (Like a conveyor belt, filter and filter again and again, and then output)
- Put the element on it.
- Then use this streamlined API to conveniently manipulate elements.
(2) Acquisition of Stream:
The first step for Stream to operate a collection or array is to get the Stream stream first, and then the stream function can be used.
1. Three types of Stream methods:
- Get the Stream stream:
- Create a pipeline and put data on the pipeline ready for operation.
- Intermediate method:
- operations on the pipeline. After one operation is completed, other operations can be continued.
- Termination method:
- A Stream can only have one final method, which is the last operation on the pipeline.
2. The way the collection obtains the Stream:
- Streams can be generated using the default method stream() in the Collection interface
name | illustrate |
default Stream<E> stream() | Get the Stream of the current collection object |
3. The way to get the Stream from the array:
name | illustrate |
public static <T> Stream<T> stream(T[] array) | Get the Stream of the current array |
public static<T> Stream<T> of(T... values) | Get the Stream of the current array/variable data |
import java.util.*;
import java.util.stream.Stream;
/**
* 获取Stream流
*/
public class StreamDemo02 {
public static void main(String[] args) {
//1.集合获取Stream流
//1.1Collection集合获取流
Collection<String> list = new ArrayList<>();
Stream<String> s = list.stream();
//1.2Map集合获取流
Map<String,Integer> maps = new HashMap<>();
//对键获取流
Stream<String> keyStream = maps.keySet().stream();
//对值获取流
Stream<Integer> valueStream = maps.values().stream();
//键值对流 entrySet()==>将Map转Set
Stream<Map.Entry<String,Integer>> kvStream = maps.entrySet().stream();
//2.数组获取流
String[] names = {"大大","小小","青青","晨晨"};
Stream<String> arrStream = Arrays.stream(names);//方式1
Stream<String> arrStream01 = Stream.of(names);//方式2
}
}
4. Commonly used APIs of Stream (intermediate operation method)
- The intermediate method is also called a non-terminal method. After the call is completed, a new Stream is returned and can be used continuously, which supports chain programming.
- Data in collections and arrays cannot be directly modified in Stream.
name | illustrate |
Stream<T> filter(Predicate<? super T> predicate) | Used to filter the data in the stream |
Stream<T> limit(long maxSize) | Get the first few elements |
Stream<T> skip(long n) | skip the first few elements |
Stream<T> distinct() | Remove duplicate elements in the stream, depending on (hashCode and equals methods) |
static <T> Stream<T> concat(Stream a,Stream b) | Merge two streams a and b into one stream |
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.stream.Stream;
/**
* Stream流常用的API
*/
public class StreamDemo03 {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("大大");
list.add("小小");
list.add("小青青");
list.add("小晨晨");
//找出集合元素以小开头的元素
//1. 用于对流中的数据进行过滤 Stream<T> filter(Predicate<? super T> predicate)
// list.stream().filter(new Predicate<String>() {
// @Override
// public boolean test(String s) {
// return s.startsWith("小");
// }
// });
//简化1
//
// list.stream().filter( s -> s.startsWith("小")).forEach(new Consumer<String>() {
// @Override
// public void accept(String s) {
// System.out.println(s);
// }
// });
//简化2
list.stream().filter( s -> s.startsWith("小")).forEach( s -> System.out.println(s));
//统计集合元素长度等于3的个数
long size = list.stream().filter(s -> s.length() == 3).count();
System.out.println(size);
//2.获取前几个元素 Stream<T> limit(long maxSize)
//list.stream().filter(s -> s.startsWith("小")).limit(2).forEach(s -> System.out.println(s));
//简化
list.stream().filter(s -> s.startsWith("小")).limit(2).forEach(System.out::println);
//3.跳过前几个元素 Stream<T> skip(long n)
list.stream().filter(s -> s.startsWith("小")).skip(2).forEach(System.out::println);
//4.map加工方法:第一个参数是原材料,第二个参数是加工后的结果
//给集合元素前面加一个,我的
list.stream().map(s -> "我的" + s).forEach(System.out::println);
//5.合并a和b两个流为一个流 static <T> Stream<T> concat(Stream a,Stream b)
Stream<String> s1 = list.stream().filter(s -> s.startsWith("小"));
Stream<Integer> s2 = Stream.of(1,2);
Stream<Object> s3 = Stream.concat(s1,s2);
s3.forEach(System.out::println);
}
}
5. The common ultimate operation method of Stream:
- The ultimate operation method, the stream cannot be used after the call is completed, because the Stream will not be returned
name | illustrate |
void forEach(Consumer action) | performs a traversal operation on each element of this stream |
long count() | returns the number of elements in this stream |
(3) Stream collection:
1. The meaning of collecting Stream:
- The meaning of collecting the Stream stream is to transfer the result data after the Stream stream operation back to the collection or array.
2. Stream collection method:
name | illustrate |
R collect(Collector collector) | Start collecting Streams and specify collectors |
The Collectors tool class provides specific collection methods:
name | illustrate |
public static <T> Collector toList() | Collect the elements into the List collection |
public static <T> Collector toSet() | Collect the elements into the Set collection |
public static Collector toMap(Function keyMapper,Function valueMapper) | Collect the elements into the Map collection |
===================================================