JDK8新特性之stream(),
学习Stream之前建议先学Lambda的相关知识
使用实例:
Class Person {
private String name;
private int age;
...
}
List<Person> list = new ArrayList<>();
list.add(new Person("jack", 20));
list.add(new Person("mike", 25));
list.add(new Person("tom", 30));
使用方法:
1、stream() / parallelStream() :将集合转为流
List list = new ArrayList();
// return Stream<E>
list.stream();
2、filter(T -> boolean):保留boolean的元素
//保留年龄为 20 的 person 元素
list = list.stream()
.filter(person -> person.getAge() == 20)
.collect(toList());
//打印输出 [Person{name='jack', age=20}]
注:collect(toList()) 可以把流转换为 List 类型
3、distinct() :去除重复元素
4、sorted() / sorted((T, T) -> int):对元素进行排序
前提:流中的元素的类实现了 Comparable 接口
//根据年龄大小来比较:
list = list.stream()
.sorted((p1, p2) -> p1.getAge() - p2.getAge())
.collect(toList());
简化版:
list = list.stream()
.sorted(Comparator.comparingInt(Person::getAge))
.collect(toList());
5、limit(long n):返回前 n 个元素
list = list.stream()
.limit(2)
.collect(toList());
//打印输出 [Person{name='jack', age=20}, Person{name='mike', age=25}]
6、skip(long n):去除前 n 个元素
list = list.stream()
.skip(2)
.collect(toList());
//打印输出 [Person{name='tom', age=30}]
- 用在 limit(n) 前面时,先去除前 m 个元素再返回剩余元素的前 n 个元素
- limit(n) 用在 skip(m) 前面时,先返回前 n 个元素再在剩余的 n 个元素中去除 m 个元素
list = list.stream()
.limit(2)
.skip(1)
.collect(toList());
//打印输出 [Person{name='mike', age=25}]
7、map(T -> R):将流中的每一个元素 T 映射为 R(类似类型转换)
//newlist 里面的元素为 list 中每一个 Person 对象的 name 变量
List<String> newlist = list.stream().map(Person::getName).collect(toList());
8、count():返回流中元素个数,结果为 long 类型
9、collect():收集方法
//toList
//toSet
//toCollection
List newlist = list.stream.collect(toList());
9.1、joining :连接字符串
注:是一个比较常用的方法,对流里面的字符串元素进行连接,其底层实现用的是专门用于字符串连接的 StringBuilder。
String s = list.stream().map(Person::getName).collect(joining(","));
//结果:jack,mike,tom
9.2、maxBy/minBy :取最值
//取age最大值
Optional<Person> optional = list.stream().collect(maxBy(comparing(Person::getAge)));
10、forEach():循环遍历
//打印各个元素:
list.stream().forEach(System.out::println);
文章最后发布于: 2019-10-21 11:41:47
本站文章为和通数据库网友分享或者投稿,欢迎任何形式的转载,但请务必注明出处.
同时文章内容如有侵犯了您的权益,请联系QQ:970679559,我们会在尽快处理。