Java8中的Stream的Map、Filter、limit、去重,删除之前的元素,最⼤值,最⼩
java stream值
Stream中常⽤的⽅法
Steam的优势
在项⽬中经常⽤到集合,遍历集合lambda表达式,要对集合进⾏过滤和排序,Stream就派上⽤场了。Stream作为java1.8的新特性,基于lambda表达式,它专注于对集合对象进⾏各种⾼效、可以让你从常⽤的if、else、for⾥⾯跳出来。提⾼了编程效率和代码可读性。
常⽤⽅法
Filter 过滤
⼀条数据过滤
List<Partner> result = byParentUid.stream()
.filter((Partner p) -> p.getGrade().equals("程序员"))
.List());
多条数据过滤
List<Integer> age = new ArrayList<Integer>();
age.add(1);
age.add(2);
List<Partner> result = byParentUid.stream()
.filter((Partner p) -> Grade()))
.List());
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( )).List( ));
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)-> Integerpare( Id( ),Id( )) ).get( ); System.out.String());
}
输出结果
Student{id=1,name='⼩王',addresses='浙江'}
最⼤值同理,靠你们补了

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。