天津科技制造有限公司seo整站优化哪家专业
一、概述
lambda表达式是JDK8中的一个新特性,对某些匿名内部类进行简化,是函数式编程;
二、基本格式
(参数列表)->{方法体代码}
三、Stream流
是jdk8中的新特性,将数据以流的形式进行操作
三、常用方法解析
3.1、准备工作
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode //用于后期的去重使用
@Data
public class People {private int id;private String name;private int age;private String home;private List<Friend> friendList;
}
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode //用于后期的去重使用
@Data
public class Friend {private int id;private String name;private int age;private String home;private String category;//分类
}
void contextLoads() {People people1=new People(1,"曹操",33,"魏国",null);People people2=new People(2,"孙权",15,"吴国",null);People people3=new People(3,"张飞",14,"蜀国",null);People people4=new People(3,"张飞",14,"蜀国",null);List<Friend>list1=new ArrayList<>();List<Friend>list2=new ArrayList<>();List<Friend>list3=new ArrayList<>();list1.add(new Friend(1,"刘备",88,"河北,石家庄","好朋友"));list1.add(new Friend(2,"赵云",99,"湖北,武汉","新朋友"));list2.add(new Friend(3,"周瑜",85,"辽宁,大连","老朋友"));list2.add(new Friend(3,"周瑜",85,"辽宁,大连","老朋友"));list2.add(new Friend(4,"诸葛亮",56,"内蒙古,包头","大朋友"));list3.add(new Friend(5,"郭嘉",56,"甘肃,兰州","骄傲的朋友"));list3.add(new Friend(6,"吕布",100,"陕西,西安","厉害的朋友"));list3.add(new Friend(7,"吕布",100,"陕西,西安","厉害的朋友"));people1.setFriendList(list1);people2.setFriendList(list2);people3.setFriendList(list3);people4.setFriendList(list3);List<People>peopleList=new ArrayList<>(Arrays.asList(people1,people2,people3,people4));}
3.2、常用方法
stream() forEach() | //打印people年龄小于18的人的名字,且去重peopleList.stream().distinct().filter(new Predicate<People>() {@Overridepublic boolean test(People people) {return people.getAge()<18;}}).forEach(new Consumer<People>() {@Overridepublic void accept(People people) {System.out.println(people.getName());}});-------------------------------Alt+Enter转为Lambda表达式----------------------------- peopleList.stream().distinct().filter(people -> people.getAge()<18).forEach(people -> System.out.println(people.getName())); |