Stream中常用的方法
Steam的优势常用方法Filter 过滤Map方法Limit限制返回个数Distinct 去重操作skip 删除之前的元素min 最小值
Steam的优势
在项目中经常用到集合,遍历集合lambda表达式,要对集合进行过滤和排序,Stream就派上用场了。Stream作为java1.8的新特性,基于lambda表达式,它专注于对集合对象进行各种高效、可以让你从常用的if、else、for里面跳出来。提高了编程效率和代码可读性。
常用方法
Filter 过滤
一条数据过滤
List<Partner> result = byParentUid.stream()
.filter((Partner p) -> p.getGrade().equals("程序员"))
.collect(Collectors.toList());
多条数据过滤
List<Integer> age = new ArrayList<Integer>();
age.add(1);
age.add(2);
List<Partner> result = byParentUid.stream()
.filter((Partner p) -> age.contains(p.getGrade()))
.collect(Collectors.toList());
Map方法
Student a1 = new Student( 1,"小王","浙江" );
Student a2 = new Student( 2,"小黄",“湖北" );
Student a3 = new Student( 3,“小皇",“北京" );
List<Student> students = new ArrayList<>( );
students.add(a1);
students.add(a2);
students.add(a3);
private static void testMap(List<Student> students) {
//只获取地址输出
List<String> addresses = students.stream( ).map( s ->"住
址: "+s.getAddress( )).collect(Collectors.toList( ));
addresses.forEach( a ->System.out.println(a ) );
输出结果
住址:浙江
住址:湖北
住址:北京
Limit限制返回个数
public static void main(String
[ ] args
) {
List
<String> list
= Arrays
.asList( "1" ,"2","3","1" ,"2" );
list
.stream( ). limit(2). forEach( System
.out
: :println
);
输出结果
1
2
Distinct 去重操作
public static void main(String [ ] args) {
//字符串的去重
List<String> list = Arrays.asList( "1" ,"2","3","1" ,"2" );
list.stream( ).distinct( ). forEach( System.out: :println);
}
输出结果
1
2
3
skip 删除之前的元素
public static void main(String [] args) {
List<String> list = Arrays.asList( "1" ,"2","3","1" ,"2" );
list.stream( ).skip(2). forEach(System.out: :println) ;
}
输出结果
3
1
2
min 最小值
Student a1 = new Student( 1,"小王","浙江");
Student a2 = new Student( 2,"小黄",“湖北");
Student a3 = new Student( 3,“小皇",“北京");
List<Student> students = new ArrayList<>( );
students.add(a1);
students.add(a2);
students.add(a3);
Student min = students.stream().min((stu1,stu2)-> Integer.compare( stu1.getId( ),stu2.getId( )) ).get( );
System.out.println(min.toString());
}
输出结果
Student{id=1,name='小王',addresses='浙江'}
最大值同理,靠你们补了