常用API
List<Employee> emps = Arrays.asList(
new Employee(101, "张三", 18, 9999.99),
new Employee(102, "李四", 59, 6666.66),
new Employee(103, "王五", 28, 3333.33),
new Employee(104, "赵六", 8, 7777.77),
new Employee(105, "田七", 38, 5555.55),
new Employee(105, "田七", 38, 5555.55)
);
List<String> stringList = Arrays.asList("aaa", "bbb", "ccc");
/*
过滤和切片
*/
// filet 过滤
List<Employee> list = emps.stream().filter(e -> e.getAge() > 35).collect(Collectors.toList());
// limit(n) 限定前n个数量
List<Employee> list1 = emps.stream().limit(3).collect(Collectors.toList());
// skip(n) 跳过前n个元素
List<Employee> list2 = emps.stream().skip(2).collect(Collectors.toList());
// distinct 去重(需要hashcode()和equals()支持)
List<Employee> list3 = emps.stream().distinct().collect(Collectors.toList());
/*
map映射(将流中每个元素应用于函数)
*/
// 转大写
List<String> list4 = stringList.stream().map(str -> str.toUpperCase()).collect(Collectors.toList());
List<String> list5 = stringList.stream().map(String::toUpperCase).collect(Collectors.toList());
// 提取名字
List<String> list6 = emps.stream().map(emp -> emp.getName()).collect(Collectors.toList());
List<String> list7 = emps.stream().map(Employee::getName).collect(Collectors.toList());
/*
排序
*/
// 自然排序
List<String> list8 = stringList.stream().sorted().collect(Collectors.toList());
// 定制排序:按年龄正序排序,如果年龄相同,按姓名排序
List<Employee> list9 = emps.stream().sorted((x, y) -> {
if (x.getAge() == y.getAge()) {
return x.getName().compareTo(y.getName());
} else {
return x.getAge() - y.getAge();
}
}).collect(Collectors.toList());
/*
匹配和查找
*/
// 任意匹配
boolean b = emps.stream().anyMatch(x -> x.getName().equals("张三"));
// 最大值
Optional<Employee> emp = emps.stream().max((x, y) -> (int) (x.getSalary() - y.getSalary()));
// 最大工资是多少
Optional<Double> max = emps.stream().map(s -> s.getSalary()).max(Double::compare);
System.out.println(max.get() == 9999.99);
/*
规约 reduce
*/
// 计算工资总和
Optional<Double> sumSal = emps.stream().map(x -> x.getSalary()).reduce(Double::sum);
System.out.println(sumSal.get());
/*
收集 collect()
*/
// 收集姓名,放到set集合中
Set<String> set = emps.stream().map(s -> s.getName()).collect(Collectors.toSet());
// 平均工资
Double avgSal = emps.stream().collect(Collectors.averagingDouble(x -> x.getSalary()));
/*
分组
*/
// 按年龄分组
Map<Integer, List<Employee>> collect = emps.stream().collect(Collectors.groupingBy(x -> x.getAge()));
// 多级分组(先按照年龄分组,再按照工资分组)
Map<Integer, Map<String, List<Employee>>> integerMapMap = emps.stream().collect(Collectors.groupingBy(x -> x.getAge(), Collectors.groupingBy(y -> {
if (y.getSalary() <= 5000) {
return "低工资";
} else {
return "高工资";
}
})));
/*
分片(分区)
*/
// 工资是否大于8000,分区(满足true和不满足false条件的两个区)
Map<Boolean, List<Employee>> map = emps.stream().collect(Collectors.partitioningBy(x -> x.getSalary() > 8000));
List<Employee> trueList = map.get(true);
List<Employee> falseList = map.get(false);
本文含有隐藏内容,请 开通VIP 后查看