public class Java8Test {
public static class Staff {
private String name;
private int age;
private BigDecimal salary;
public Staff(String name, BigDecimal salary, int age) {
this.name = name;
this.salary = salary;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public BigDecimal getSalary() {
return salary;
}
}
public static void main(String[] args) {
List<Staff> list = new ArrayList<>();
list.add(new Staff("测试", new BigDecimal("8.8"), 18));
list.add(new Staff("后端", new BigDecimal("18.8"), 20));
list.add(new Staff("运维", new BigDecimal("12.8"), 19));
list.add(new Staff("DBA", new BigDecimal("13.8"), 22));
list.add(new Staff("前端", new BigDecimal("13.8"), 22));
list.add(new Staff("前端", new BigDecimal("14.8"), 26));
list.add(new Staff("运营", new BigDecimal("9.8"), 24));
list.add(new Staff("产品", new BigDecimal("16.8"), 21));
list.add(new Staff("经理", new BigDecimal("34.8"), 25));
list.add(new Staff("产品", new BigDecimal("23.8"), 28));
//遍历List
list.stream().forEach(staff -> {
if("测试".equals(staff.getName())){
System.out.println(staff);
}
});
//挑出 产品 岗位的人
List<Staff> productors = list.stream().filter(staff -> "产品".equals(staff.getName())).collect(Collectors.toList());
//拆分成两个集合,true-年龄超过20岁,false-年龄低于20岁
Map<Boolean, List<Staff>> resultMap = list.stream().collect(Collectors.partitioningBy(staff -> staff.getAge() >= 20));
//求总年龄
int allAge = list.stream().mapToInt(staff -> staff.getAge()).sum();
//求年龄大于20岁的总薪水
BigDecimal allSalary = list.stream().filter(staff -> staff.getAge() > 20)
.map(staff -> staff.getSalary())
.reduce(BigDecimal.ZERO, BigDecimal::add);
//按年龄从大到小排序Name
//现在推荐这样写:Comparator.comparing(Staff::getAge)
List<Staff> staffs = list.stream().sorted((s1, s2) -> ((Integer)s1.getAge()).compareTo(s2.getAge())).collect(Collectors.toList());
//求年龄最小的两位
List<Staff> littleStaffs = staffs.stream().limit(2).collect(Collectors.toList());
//去掉岗位重复的记录(名字重复)
List<Staff> distinctStaff = list.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(e->e.getName()))), ArrayList::new));
//去掉岗位重复的记录(名字+年龄重复)
distinctStaff = list.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(e->e.getName()+";"+e.getAge()))), ArrayList::new));
//按岗位进行分组统计人数
Map<String, Integer> map = list.stream().collect(Collectors.groupingBy(Staff::getName, Collectors.summingInt(p -> 1)));
}
}
另外,stream()方法,也可以被parallelStream()代替。
使用parallelStream就能立即获得一个拥有并行能力的流,利用好并行化非常重要。不过并不是所有的流计算都要使用并行化流操作,只有当计算机是多核并且集合数据量较大(超过一万)的时候使用并行化流操作可以提高效率。