Stream是对集合(Collection)对象功能的增强,专注于对集合对象进行各种非常便利、高效的聚合操作(aggregate operation),或大批量数据操作 (bulk data operation)。
Stream API 借助于同样新出现的 Lambda 表达式,极大的提高编程效率和程序可读性的同时提供串行和并行两种模式进行汇聚操作,并发模式能够充分利用多核处理器的优势,使用 fork/join 并行方式来拆分任务和加速处理过程。
将要处理的元素集合看作一种流, 流在管道中传输, 并且可以在管道的节点上进行处理, 比如筛选, 排序,聚合等经过这些中间操作(intermediate operation)的处理,最后由最终操作(terminal operation)得到前面处理的结果。
代码实例:
先引一个对象作为操作的基础:
List<Employee> employees = Arrays.asList(
new Employee("张三", 18, 222.22, Employee.Status.FREE),
new Employee("李四", 18, 111.22, Employee.Status.BUSY),
new Employee("王五", 18, 221.22, Employee.Status.VOCATION),
new Employee("赵六", 18 , 333.22, Employee.Status.FREE)
);
中间操作:
//region 中间操作——流水线——中间操作不会执行处理
/**
* 筛选与切片
* filter 接受lambda 从流中排除某些元素
* limit 截断流,使其元素不超过给定数量
* skip(n) 跳过元素,返回一个扔掉了前n个元素的流,若流中不足n个,返回一个空流
* distinct 筛选,通过流所生成元素的hashCode()和equals()去除::元素类需要重写hashCode和equals方法
*/
@Test
public void test2() {
//中间操作
employees.stream()
.filter((e) -> {
System.out.println("跑路");//&& || 找到了就不再执行
return e.getAge() > 35;
})
.limit(2)
.skip(1)
.distinct()
.forEach(System.out::println);//终止操作
//终止操作 惰性求值:一次性处理
// stream.forEach(System.out::println);
}
//外部迭代,s
@Test
public void test3() {
Iterator<Employee> it = employees.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
}
//endregion
map映射,用于映射每个元素到对应的结果
例子一;
List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);
// 获取对应的平方数
List<Integer> squaresList = numbers.stream().map( i -> i*i).distinct().collect(Collectors.toList());
例子二;提取合并字符串
/**
* map 接受lambda,将元素转换成其他形式或提取信息
* map接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素
* flatMap 接收一个函数作为参数,将流中每个值都换成另个流,然后把所有流连接成一个流
*/
@Test
public void test5() {
List<String> list = Arrays.asList("aaa", "bbb", "ccc", "ddd");
list.stream()//获取流
.map((str) -> str.toUpperCase())//函数
.forEach(System.out::println);
Stream<Stream<Character>> streamStream = list.stream()
.map(TESTStreamAPI::filterCharacter);//{{a,a,a},{b,b,b}……}
streamStream.forEach((sm) -> {
sm.forEach(System.out::println);
//flatMap 接收一函数作参数,将流中每个值都换成另个流并合成一个流
Stream<Character> sm2 = list.stream()
.flatMap(TESTStreamAPI::filterCharacter);//{a,a,a,b,b,b……}
sm2.forEach(System.out::println);
});
}
public static Stream<Character> filterCharacter(String str) {
List<Character> list = new ArrayList<>();
for (Character character : str.toCharArray()) {
list.add(character);
}
return list.stream();
}
查找与匹配:
@Test
public void test11(){
boolean boolean1 = employees.stream()
.allMatch((e)->e.getStatus().equals(Employee.Status.BUSY));//allMatch——检查是否匹配所有元素
boolean bool2 = employees.stream()
.anyMatch((e) -> e.getStatus().equals(Employee.Status.BUSY));//anyMatc——检查是否只是匹配一个元素
boolean b3 = employees.stream()
.noneMatch((e) ->e.getStatus().equals(Employee.Status.BUSY));//noneMatch——是否没有匹配所有元素
Optional<Employee> employeeOptional = employees.stream()
.sorted((e1,e2)-> -Double.compare(e1.getSalary(),e2.getSalary()))
.findFirst();//findFirst——返回符合条件的第一个元素,sort排序选取的最低的,"-" 获取最高的
Optional<Employee> employeeOptional2 = employees.parallelStream()//parallelsteam获取并行(多个线程同时找,谁先找到用谁),stream串行(一个一个找)
.filter((e)-> e.getStatus().equals(Employee.Status.FREE))
.findAny();//findany返回当前流中任意元素
Long count = employees.stream()
.count();//返回流中元素总个数 终止操作
Optional<Employee> maxOptionalEmployee = employees.stream()
.max((e1,e2)-> Double.compare(e1.getSalary(),e2.getSalary()));//终止操作 max流中元素最大值
Optional<Double> minOptionalEmployee = employees.stream()
.map(Employee::getSalary)
.min(Double::compare);//终止操作最小值
}
归约:合并
@Test
public void test1() {
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
Integer sum = list.stream()
.reduce(0, (x, y) -> x + y);//从0开始结合上面的list累加
Optional<Double> op = employees.stream()
.map(Employee::getSalary)//得到工资
.reduce(Double::sum);//工资getSalary总和sum
}
收集:合并、分组
//region 收集collect(Collector c) 将流转换为其他形式,接收一个Collector接口的实现
/**
* Collector接口中方法实现决定了怎么对流执行收集操作(收集到是List、set还是map)
* 其实现类提供了很多静态方法,方便地创建常见收集器实例
*/
@Test
public void test2() {
//region Collector接口中方法实现决定了如何对流执行收集操作(收集到List、set、map)
List<String> list = employees.stream()
.map(Employee::getName)
.collect(Collectors.toList());//接口中方法实现 将流收集到list中
list.forEach(System.out::println);
Set<String> set = employees.stream()
.map(Employee::getName)
.collect(Collectors.toSet());//接口中方法实现 将流收集到set中
set.forEach(System.out::println);
HashSet<String> hashSet = employees.stream()
.map(Employee::getName)
.collect(Collectors.toCollection(HashSet::new));//接口中方法实现 将流收集到map中
hashSet.forEach(System.out::println);
//endregion
//region 其实现类提供了很多静态方法,方便地创建常见收集器实例
Long count = employees.stream()
.collect(Collectors.counting());//总数
Double avg = employees.stream()
.collect(Collectors.averagingDouble(Employee::getSalary));//平均值
Double sum = employees.stream()
.collect(Collectors.summingDouble(Employee::getSalary));//总和
Optional<Employee> max = employees.stream()
.collect(Collectors.maxBy((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary())));//最大值
Optional<Double> min = employees.stream()
.map(Employee::getSalary)
.collect(Collectors.minBy(Double::compare));//最小值
//endregion
//region 分组
Map<Employee.Status, List<Employee>> map = employees.stream()
.collect(Collectors.groupingBy(Employee::getStatus));
Map<Employee.Status, Map<String, List<Employee>>> mapMap = employees.stream()//先根据状态再根据年级
.collect(Collectors.groupingBy(Employee::getStatus, Collectors.groupingBy((e) -> {
if (((Employee) e).getAge() <= 35) {
return "青年";
} else if (((Employee) e).getAge() <= 50) {
return "中年";
} else {
return "老年";
}
})));
Map<Boolean,List<Employee>> booleanListMap = employees.stream()
.collect(Collectors.partitioningBy((e)->e.getSalary()>8000));//分区,符合的一个区不符合的一个区false=[] true=[]
DoubleSummaryStatistics doubleSummaryStatistics = employees.stream()
.collect(Collectors.summarizingDouble(Employee::getSalary));
doubleSummaryStatistics.getAverage();//平均值、最大、最小
String str = employees.stream()
.map(Employee::getName)
.collect(Collectors.joining(","));//分隔符,(“,”,“---”,“------”)后三个是开头和结尾
//endregion
}
//endregion
小结:
菜鸟教程 菜鸟不菜,加油
java8 中streams api详解
流从操作类型:
- Intermediate(转换操作):后跟随0个多个intermediate操作,打开流、数据映射或过滤,返回流,交个下一个操作,lazy(只会在 Terminal 操作的时候融合起来,一次循环完成)
- Terminal:一个一次,最后一个操作,真正开始流的遍历,生成一个结果或side effect
- 总:Stream 里有个操作函数的集合,每次转换操作就是把转换函数放入这个集合中,在 Terminal 操作的时候循环 Stream 对应的集合,然后对每个元素执行所有的函数。
- short-circuting:必要非充分条件(当操作一个无限大的 Stream,而又希望在有限时间内完成操作)