Stream流
Stream流的思想
- 先得到集合或数组的Stream流
- 把元素放上
- 用Stream流简化的API来方便操作元素
package Stream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Demo01 {
public static void main(String[] args) {
List<String> names = new ArrayList<>();
Collections.addAll(names, "张三丰", "张无忌", "赵敏", "张强");
System.out.println(names);
//支持链式编程
names.stream().filter(s -> s.startsWith("张")).filter(s -> s.length() == 3).forEach(s -> System.out.println(s));
}
}
获取Stream流的方式
-
集合获取
使用Collection接口中的默认方法stream()生成流
-
数组获取
使用Array方法和Stream提供的方法
package Stream;
import java.util.*;
import java.util.stream.Stream;
public class Demo02 {
public static void main(String[] args) {
//Collection集合
Collection<String> list = new ArrayList<>();
Stream<String> s = list.stream();
//Map集合
Map<String, Integer> maps = new HashMap<>();
Stream<String> value = maps.keySet().stream();
Stream<Integer> key = maps.values().stream();
Stream<Map.Entry<String, Integer>> keyAndValue = maps.entrySet().stream();
//数组
String[] name = {"张无忌", "张三丰", "张翠山", "张强"};
Stream<String> nameStream1 = Arrays.stream(name);
Stream<String> nameStream2 = Stream.of(name);
}
}
Stream流的常用API
count:统计个数
filter:过滤元素
limit:取前几个元素
skip:跳过前几个
map:加工方法