注: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(longn):返回前n个元素list=list.stream().limit(2).collect(toList());//打印输出[Person{name='jack',age=20},Person{name='mike',age=25}]6、skip(longn):去除前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//toCollectionListnewlist=list.stream.collect(toList());
9.1、joining:连接字符串
注:是一个比较常用的方法,对流里面的字符串元素进行连接,其底层实现用的是专门用于字符串连接的StringBuilder。
Strings=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);