最近在开发的过程中,发现了大量的lambda表达式,看着帅气而有简洁的代码,我也有点心动了,于是学习了其用法,lambda概念以及特点我在这里就不多作概述了,不懂的朋友可以自行去了解下,在这里我直接上代码,不喜无喷!!
一:添加一些基类和原始数据
public class Deptment {
private String name;
private String address;
//省略setter,getter等方法
}
public class Person {
private String firstName;
private String lastName;
private String job;
private String gender;
private int salary;
private int age;
//省略setter,getter等方法
}
//测试类
public class TestMain {
private static List<Person> javaProgrammers;
static {
javaProgrammers = new ArrayList<Person>() {
{
add(new Person("Elsdon", "Jaycob", "Java programmer", "male", 43, 2000));
add(new Person("Tamsen", "Brittany", "Java programmer", "female", 23, 1500));
add(new Person("Floyd", "Donny", "Java programmer", "male", 33, 1800));
add(new Person("Sindy", "Jonie", "Java programmer", "female", 32, 1600));
add(new Person("Vere", "Hervey", "Java programmer", "male", 22, 1200));
add(new Person("Maude", "Jaimie", "Java programmer", "female", 27, 1900));
add(new Person("Shawn", "Randall", "Java programmer", "male", 30, 2300));
add(new Person("Jayden", "Corrina", "Java programmer", "female", 35, 1700));
add(new Person("Palmer", "Dene", "Java programmer", "male", 33, 2000));
add(new Person("Addison", "Pam", "Java programmer", "female", 34, 1300));
}
};
}
public static void main(String[] args) {
//在此执行下面的操作
}
}
1、forEach():遍历
javaProgrammers.forEach( p -> {
System.out.println(p);
});
2、map():改变集合中的数据后得到新的集合
//获取所有姓名
List<String> list = javaProgrammers.stream()
.map(p -> p.getFirstName())
.collect(Collectors.toList());
2.1、peek():改变原有集合中的某个属性值,其余值不变
//每个程序员的工资改为5000
List<Person> list = javaProgrammers.stream()
.peek(p -> p.setSalary(5000))
.collect(Collectors.toList());
3、filter():过滤
//查询月薪超过 $1,400 的PHP程序员
List<Person> list9 = phpProgrammers.stream()
.filter(p -> p.getSalary() >1400)
.collect(Collectors.toList());
//下面是年龄大于 34岁且月薪在$1,400以上的女PHP程序员
List<Person> list3 = phpProgrammers.stream()
.filter(p -> p.getAge() > 34)
.filter(p -> p.getSalary() >1400 )
.collect(Collectors.toList());
//重用filter ,年龄大于 24岁的女性 Java programmers:
Predicate<Person> ageFilter = (p) -> (p.getAge() > 25);
Predicate<Person> salaryFilter = (p) -> (p.getSalary() > 1400);
Predicate<Person> genderFilter = (p) -> ("female".equals(p.getGender()));
List<Person> list4 = javaProgrammers.stream()
.filter(ageFilter)
.filter(genderFilter)
.collect(Collectors.toList());
4、limit():限制集合个数
//获取前三个数据
List<Person> list3 = javaProgrammers.stream()
.limit(3)
.collect(Collectors.toList());
5、sorted():排序
//按照姓名排序(字符串排序)
List<Person> list5 = javaProgrammers.stream()
.sorted((p1,p2) -> p1.getFirstName().compareTo(p2.getFirstName()))
.collect(Collectors.toList());
//List<Person> list5 = javaProgrammers.stream()
// .sorted(Comparator.comparing(Person::getFirstName))
// .collect(Collectors.toList());
//按照工资排序(数值排序)
List<Person> list6 = javaProgrammers.stream()
.sorted((p1,p2) -> p1.getSalary()- p2.getSalary())
.collect(Collectors.toList());
6、min():最小的一个数据,max():最大的一个数据
//工资最低的 Java programmer
Person person8 = javaProgrammers.stream()
.min((p1,p2) -> p1.getSalary() -p2.getSalary())
.get();
7、getMax():计算集合中的最大值; getMin():计算集合中的最小值; getSum():计算集合中的总和; getAverage():计算集合中 的平均值;
//最低工资是多少
long min = javaProgrammers.stream()
.mapToInt(p -> p.getSalary()).summaryStatistics()
.getMin();
8、joining():将数据拼接
//将所有姓名以逗号隔开拼接
String collect = javaProgrammers.stream()
.map(p -> p.getFirstName())
.collect(Collectors.joining(","));
9、toMap():集合转map
//以姓名为可以,Person为value
Map<String, Person> map = javaProgrammers.stream()
.collect(Collectors.toMap(
Person::getFirstName,//key
p -> p,//value
(v,u) -> v)//避免重复,可以不写
);
10、groupingBy():分组
//以性别为key,List<Person> 为value
Map<String, List<Person>> map2 =javaProgrammers.stream()
.collect(Collectors.groupingBy(Person::getGender));
11、flatMap():和map功能相似,但是其是将stream合并
//添加一些数据
List<Person> list = new ArrayList<>();
Person person1 = new Person("Jarrod", "Pace", "PHP programmer", "male", 34, 1550);
Person person2= new Person("Vere", "Hervey", "Java programmer", "male", 22, 1200);
Deptment deptment1 = new Deptment("研发一部", "深圳");
Deptment deptment2 = new Deptment("研发二部", "上海");
Deptment deptment3 = new Deptment("研发三部", "北京");
Deptment deptment4 = new Deptment("研发四部", "广州");
List<Deptment> list1 = new ArrayList<>();
List<Deptment> list2 = new ArrayList<>();
list1.add(deptment1);
list1.add(deptment2);
list2.add(deptment3);
list2.add(deptment4);
person1.setDepts(list1);
person2.setDepts(list2);
list.add(person1);
list.add(person2);
list.stream().forEach(System.out::println);
//打印结果
Person [firstName=Jarrod, lastName=Pace, job=PHP programmer, gender=male, salary=1550, age=34, depts=[Deptment [name=研发一部, address=深圳], Deptment [name=研发二部, address=上海]]]
Person [firstName=Vere, lastName=Hervey, job=Java programmer, gender=male, salary=1200, age=22, depts=[Deptment [name=研发三部, address=北京], Deptment [name=研发四部, address=广州]]]
//需求,获取所有的Deptment,利于map()得到结果如下
List<List<Deptment>> list7 = list.stream().map(p -> p.getDepts()).collect(Collectors.toList());
list7.forEach(System.out::println);
//结果
[Deptment [name=研发一部, address=深圳], Deptment [name=研发二部, address=上海]]
[Deptment [name=研发三部, address=北京], Deptment [name=研发四部, address=广州]]
//利于flatMap()得到结果如下
List<Deptment> list8 = list.stream().flatMap(p -> p.getDepts().stream()).collect(Collectors.toList());
//结果
Deptment [name=研发一部, address=深圳]
Deptment [name=研发二部, address=上海]
Deptment [name=研发三部, address=北京]
Deptment [name=研发四部, address=广州]
//结论:map()将多个集合合并成一个新的集合,该新的集合里还是集合,flagMap()是将多个集合合并成
//一个新的集合,该集合中的数据不再是集合,而是更细粒度的数据。
12、自定义返回值类型
//为每个java程序员涨1倍的薪水
List<Person> collect = javaProgrammers.stream()
.collect(ArrayList<Person>::new,//返回值类型
(list,person) -> {//第一个参数为返回值类型,第二个参数为原集合中的对象
person.setSalary(person.getSalary() * 2);
list.add(person);
},
(a,b) -> a.addAll(b)//a代表最后返回值类型,b代表第二部的list
// (a,b) -> a.addAll(b)也可以用ArrayList::addAll替代
);
13、集合对象属性去重
// 对集合 List<DataModelField> dataModelFields = new ArrayList<>() 去重
dataModelFields = dataModelFields.stream().collect(
Collectors.collectingAndThen(Collectors.toCollection(() ->
new TreeSet<>(Comparator.comparing(DataModelField::getId))),
ArrayList::new));