栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java8新特性-StreamAPI的使用

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java8新特性-StreamAPI的使用

StreamAPI的使用
  • Stream的操作步骤
  • 创建Stream
  • 中间操作
    • 1.筛选与切片
    • 2.映射
    • 3.排序
  • 终止操作
    • 1.查找与匹配
    • 2.归约
    • 3.收集

Stream的操作步骤

1.创建Stream
通过一个数据源(如:集合、数组),获取一个流
2.中间操作
中间操作链:对数据源的数据进行操作
3.终止操作
执行中间操作链,并产生结果

创建Stream

1.可以通过Collection系列集合提供的stream()或parallelStream()
2.通过Arrays中的静态方法stream()获取数组流
3.通过Stream类中的静态方法of()
4.创建无限流

//1.可以通过Collection系列集合提供的stream()或parallelStream()
List list = new ArrayList<>();
Stream stream1 = list.stream();​
//2.通过Arrays中的静态方法stream()获取数组流
Employee[] emps = new Employee[10];
Stream stream2 = Arrays.stream(emps);​
//3.通过Stream类中的静态方法of()
Stream stream3 = stream.of("aa","bb","cc");​
//4.创建无限流
//迭代
Stream stream4 = Stream.iterate(0,(x) -> x+2 );
stream4.limit(10).forEach(System.out::println);​
//生成
Stream.generate(() -> Math.random())      
	.limit(5)      
	.forEach(System.out::println);
中间操作 1.筛选与切片

filter-----接收Lambd,从流中排除某些元素
limit------截断流,使其元素不超过给定数量
skip(n)----跳过元素,返回一个扔掉前n个元素的流。若流中元素不足n个,则返回一个空流。与limit(n)互补
distinct—筛选,通过流所生成元素的hashCode()和equals()去除重复元素(需重写hashCode和equals方法)

List employees = Arrays.asList(
		new Employee("张三",18,9999.99),
		new Employee("李四",58,5555.55),
		new Employee("王五",26,3333.33),
		new Employee("赵六",36,6666.66),
		new Employee("田七",12,8888.88),
  	new Employee("田七",12,8888.88),
  	new Employee("田七",12,8888.88),
  	new Employee("田七",12,8888.88),
);

//filter的使用:过滤出流中年龄大于35岁的
//中间操作:不会执行任何操作
Stream stream = employees.strem()
  						.filter((e) -> {
                              System.out.println("Stream API 的中间操作");
                              return e.getAge() > 35;
                            });
//终止操作:一次性执行全部操作,即“惰性操作”
stream.forEach(System.out::println);


//limit的使用:过滤出工资大于5000的前两个
employees.stream()
  		 .filter((e) -> {
           System.out.println("短路!");
           return e.getSalary() > 5000;
         })
  		 .limit(2)
  		 .forEach(System.out::println);


//skip的使用:扔去过滤出的工资大于5000的前两个
employees.stream()
  			 .filter((e) -> {
           System.out.println("短路!");
           return e.getSalary() > 5000;
         })
  			 .skip(2)
  			 .forEach(System.out::println);


//distinct的使用:过滤出工资大于5000,然后扔去前两个元素,最后在去掉重复元素
employees.stream()
  		.filter((e) -> {
           System.out.println("短路!");
           return e.getSalary() > 5000;
         })
  		.skip(2)
  	    .distinct()
  		.forEach(System.out::println);
//注:需重写Employee类的hashCode方法和equals方法
2.映射

map-----接收Lambda,将元素转换成其他形式或提取信息。接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素
flatMap----接收一个函数作为参数,将流中的每个值都换到另一个流中,然后返回这个新流

List list = Arrays.asList("aaa","bbb","ccc","ddd","eee");

List employees = Arrays.asList(
		new Employee("张三",18,9999.99),
		new Employee("李四",58,5555.55),
		new Employee("王五",26,3333.33),
		new Employee("赵六",36,6666.66),
		new Employee("田七",12,8888.88)
);


//map的使用:将每一个元素转换成大写的
list.stream()
  	.map((str) -> str.toUpperCase())
  	.forEach(System.out::println);

//map的使用:获取每一个元素的名字
employees.stream()
  			 .map(Employee::getName)
  			 .forEach(System.out::println);


public static Stream filterCharacter(String str){
  List list = new ArrayList<>();
  for(Character ch : str.toCharArray()){
    list.add(ch);
  }
  return list.stream();
}

//方式一:使用map:获取的每一个元素对应着一个流
Stream> stream = list.stream()
  			.map(TestStreamApI::filterCharacter);
stream.forEach((sm) -> {
  sm.forEach(System.out::println);
});

//方式二:使用flatMap:获取的是一个流
Stream sm = list.stream()
  			.flatmap(TestStreamApI::filterCharacter);
sm.forEach(System.out::println);
3.排序

sorted()-------自然排序(Comparable)
sorted(Comparator com)-----定制排序(Comparator)

List list = Arrays.asList("ccc","aaa","bbb","ddd","eee");

List employees = Arrays.asList(
		new Employee("张三",18,9999.99),
		new Employee("李四",58,5555.55),
		new Employee("王五",26,3333.33),
		new Employee("赵六",36,6666.66),
		new Employee("田七",12,8888.88)
);

//自然排序的使用
list.stream()
  	.sorted()
  	.forEach(System.out::println);

//定制排序的使用
employees.stream()
  			 .sorted((e1,e2) -> {
						if(e1.getAge().equals(e2.getAge())){
              	return e1.getName().compareTo(e2.getName());
            }else{
              	return e1.getAge().compareTo(e2.getAge());
            }
         }).forEach(System.out::println);
终止操作 1.查找与匹配

allMatch----------检查是否匹配所有元素
anyMatch----------检查是否至少匹配一个元素
noneMatch---------检查是否没有匹配所有元素
findFirst---------返回第一个元素
findAny-----------返回当前流中的任意元素
count-------------返回流中元素的总个数
max---------------返回流中最大值
min---------------返回流中最小值

List employees = Arrays.asList(
		new Employee("张三",18,9999.99,Status.FREE),
		new Employee("李四",58,5555.55,Status.BUSY),
		new Employee("王五",26,3333.33,Status.VOCATION),
		new Employee("赵六",36,6666.66,Status.FREE),
		new Employee("田七",12,8888.88,Status.BUSY)
);

//allMatch的使用
boolean b1 = employees.stream()
  						.allMatch((e) -> e.getStatus().equals(Status.BUSY));
System.out.println(b1);

//anyMatch的使用
boolean b2 = employees.stream()
  						.anyMatch((e) -> e.getStatus().equals(Status.BUSY));
System.out.println(b2);

//noneMatch的使用
boolean b3 = employees.stream()
  						.noneMatch((e) -> e.getStatus().equals(Status.BUSY));
System.out.println(b3);

//findFirst的使用
Optional op = employees.stream()
  				.sorted((e1,e2) -> Double.compare(e1.getSalary(),e2.getSalary()))
  				.findFirst();
System.out.println(op.get());

//findAny的使用
Optional op2 = employees.stream()
  				.filter((e) -> e.getStatus().equals(Status.FREE))
  				.findAny();
System.out.println(op2.get());

//count的使用
Long count = employees.stream()
  						.count();
System.out.println(count);

//max的使用
Optional op1 = employees.stream()
  								.max((e1,e2) -> Double.compare(e1.getSalary(),e2.getSalary()));
System.out.println(op1.get());

//min的使用
Optional op2 = employees.stream()
  								.map(Employee::getSalary)
  								.min(Double::compare);
System.out.println(op2.get());
2.归约

reduce(T identity,BinaryOperator) / reduce(BinaryOperator)-----可以将流中元素反复结合起来,得到一个值

List list = Arrays.asList(1,2,3,4,5,6,7,8,9,10);

//方式一
//reduce的使用:将第0个元素作为x,第1个元素作为y,其和值再次作为x,第2个元素作为y,反复结合最后得到一个值
Integer sum = list.stream()
			.reduce(0,(x,y) -> x+y);
System.out.println(sum);

//方式二
//reduce的使用
Optional op = employees.stream()
  						.map(Employee::getSalary)
  						.reduce(Double::sum);
System.out.println(op.get());
3.收集

collect--------将流转换为其他形式。接收一个Collector接口的实现,用于给Stream中元素做汇总的方法

//collect的使用:转换成list
List list = employees.stream()
						.map(Employee::getName)
						.collect(Collectors.toList());
list.forEach(System.out::println);

//collect的使用:转换成set
Set set = employees.stream()
						.map(Employee::getName)
						.collect(Collectors.toSet());
set.forEach(System.out::println);

//collect的使用:转化成hashSet
HashSet hs = employees.stream()
						 .map(Employee::getName)
				 		 .collect(Collectors.toCollection(HashSet::new));
hs.forEach(System.out::println);
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/325296.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号