Stream API
是jdk8
提供的一系列的方法,专门用于操作集合。支持并行化处理数据,更加高效,提供了丰富的API
,易于使用。
特点:
Stream
不能用于存储数据,而是计算或管理数据Stream
的操作不会更新源数据(集合、数组等)Stream
的处理是一次性的,当消费一次后,不能再次消费,除非重新创建新的Stream
Stream
的操作是延迟处理,也称为惰性求值。每次操作(开始、中间),都不会执行,除非等到终止操作,才会往下执行Stream
更像一个高级的Iterator
,用于遍历读取数据的,但是更加高效① 创建 Stream 指向集合数据源
//获取串行流
Stream<String> stream = list.stream();
//获取并行流
Stream<String> parallelStream = list.parallelStream();
② 引用特定对象的实例方法
Stream stream = Arrays.stream(T[] arr);
③ 创建 Stream 指向一系列值
Stream stream = Stream.of(T,…,T);
--->
Stream<String> st = Stream.of("1", "2");
④ 创建 Stream 指向无限流
Stream stream = Stream.generate(Supplier sup);
--->
Stream.generate((()->"a"));
映射(将元素映射成任意类型)
User a = new User("tom", 1);
User b = new User("jack", 2);
List<User> users = new ArrayList<>();
users.add(a);users.add(b);
//过滤过名字 [tom,jack]
List<String> names = users.stream().map(User::getName).collect(Collectors.toList());
过滤
List<String> list = Arrays.asList("a", "b", "c");
Stream<String> stream = list.stream();
//[a]
List<String> aList = stream.filter(t -> t.equals("a")).collect(Collectors.toList());
跳过n
项
List<String> list = Arrays.asList("a", "b", "c");
Stream<String> stream = list.stream();
//[c]
List<String> aList = stream.skip(2).collect(Collectors.toList());
截取前n
项
List<String> list = Arrays.asList("a", "b", "c");
Stream<String> stream = list.stream();
//[a,b]
List<String> aList = stream.limit(2).collect(Collectors.toList());
去重
List<String> list = Arrays.asList("a", "a", "c");
Stream<String> stream = list.stream();
//[a,c]
List<String> aList = stream.distinct().collect(Collectors.toList());
排序
sort()
:自然排序
List<Integer> list = Arrays.asList(1, 3, 2);
//[1, 2, 3]
List<Integer> aList = list.stream().sorted().collect(Collectors.toList());
sorted(Comparator)
:定制排序
User a = new User("tom", 12);
User b = new User("jack", 23);
User c = new User("rose", 18);
List<User> users = new ArrayList<>();
users.add(a);users.add(b);users.add(c);
//正序[User{name='tom', age=12}, User{name='rose', age=18}, User{name='jack', age=23}]
List<User> collect = users.stream().sorted((o1,o2)->o1.getAge()-o2.getAge()).collect(Collectors.toList());
统计个数
List<Integer> list = Arrays.asList(1, 3, 2);
//3
long count = list.stream().count();
求最大、最小值
List<Integer> list = Arrays.asList(1, 3, 2);
//3
long max = list.stream().max();
//1
long max = list.stream().min();
迭代
List<Integer> list = Arrays.asList(1, 3, 2);
//1 3 2
list.stream().forEach(System.out::println);
归约(一般用于计算计算总数)
List<Integer> list = Arrays.asList(1, 3, 2);
//6
Integer sum = list.stream().reduce((a, b) -> a + b).get();
检测元素是否匹配
allMatch(Predicate)
:检测是否全部匹配anyMatch(Predicate)
:检测是否至少有一个匹配noneMatch(Predicate)
:检测是否都不匹配List<Integer> list = Arrays.asList(1, 3, 2);
//true
boolean b = list.stream().anyMatch(a -> a.equals(1));
stream
转集合
List<Integer> list = Arrays.asList(1, 3, 2);
List<Integer> alist = users.stream().collect(Collectors.toList());