java8新特性-StreamAPI的使用

本文详细介绍了Java 8中的Stream API,包括如何创建Stream、中间操作如筛选、映射和排序,以及终止操作如查找、匹配、归约和收集等。通过实例展示了Stream API在处理数据时的强大功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Stream的操作步骤

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

创建Stream

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

//1.可以通过Collection系列集合提供的stream()或parallelStream()
List<String> list = new ArrayList<>();
Stream<String> stream1 = list.stream();//2.通过Arrays中的静态方法stream()获取数组流
Employee[] emps = new Employee[10];
Stream<Employee> stream2 = Arrays.stream(emps);//3.通过Stream类中的静态方法of()
Stream<String> stream3 = stream.of("aa","bb","cc");//4.创建无限流
//迭代
Stream<Integer> 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<Employee> employees = Arrays.asList(
		new Employee("张三"189999.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<Employee> stream = employees.stream()
  						.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<String> list = Arrays.asList("aaa","bbb","ccc","ddd","eee");

List<Employee> employees = Arrays.asList(
		new Employee("张三"189999.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<Character> filterCharacter(String str){
  List<Character> list = new ArrayList<>();
  for(Character ch : str.toCharArray()){
    list.add(ch);
  }
  return list.stream();
}

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

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

3.排序

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

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

List<Employee> employees = Arrays.asList(
		new Employee("张三"189999.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<Employee> employees = Arrays.asList(
		new Employee("张三"189999.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<Employee> op = employees.stream()
  				.sorted((e1,e2) -> Double.compare(e1.getSalary(),e2.getSalary()))
  				.findFirst();
System.out.println(op.get());

//findAny的使用
Optional<Employee> 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<Employee> op1 = employees.stream()
  								.max((e1,e2) -> Double.compare(e1.getSalary(),e2.getSalary()));
System.out.println(op1.get());

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

2.归约

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

List<Integer> 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<Double> op = employees.stream()
  						.map(Employee::getSalary)
  						.reduce(Double::sum);
System.out.println(op.get());

3.收集

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

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

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

//collect的使用:转化成hashSet
HashSet<String> hs = employees.stream()
						 .map(Employee::getName)
				 		 .collect(Collectors.toCollection(HashSet::new));
hs.forEach(System.out::println);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值