java8新特性之流(Stream)操作总结

Stream概述

Stream将要处理的元素集合看作一种流,在流的过程中,借助Stream API对流中的元素进行操作,比如:筛选、排序、聚合等,给我们操作集合(Collection)提供了极大的便利。

Stream有几个特性:

  1. stream不存储数据,而是按照特定的规则对数据进行计算,一般会输出结果。
  2. stream不会改变数据源,通常情况下会产生一个新的集合或一个值。
  3. stream具有延迟执行特性,只有调用终端操作时,中间操作才会执行。

Stream流的使用

  1. 创建流
  2. 中间操作(可以有多个)
  3. 终止Stream

Stream流操作图

在这里插入图片描述

Stream流的创建(开始)

1、通过 java.util.Collection.stream() 方法用集合创建流

List<String> list = new ArrayList<String>;
// 创建一个串行(顺序)流
Stream<String> stream = list.stream();
// 创建一个并行流
Stream<String> parallelStream = list.parallelStream();

2、使用java.util.Arrays.stream(T[] array)方法用数组创建流

int[] array={1,2,3,4,5};
IntStream stream = Arrays.stream(array);

3、使用Stream的静态方法:of()

Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5, 6);

: stream是顺序流,由主线程按顺序对流执行操作,而parallelStream是并行流,内部以多线程并行执行的方式对流进行操作,但前提是流中的数据处理没有顺序要求。
如果流中的数据量足够大,并行流可以加快处速度。除了直接创建并行流,还可以通过parallel()把顺序流转换成并行流:

Stream流的使用(中间操作)

先创建一个Person类,并添加一些Person数据到List集合里面。

List<Person> list = new ArrayList<Person>();
personList.add(new Person("A", 8900,21, "male"));
personList.add(new Person("B", 7000,21, "male"));
personList.add(new Person("C", 7100,21,  "female"));
personList.add(new Person("D", 8200, 21, "female"));
personList.add(new Person("E", 9500,20,  "male"));

class Person {
	private String name;  // 姓名
	private int salary; // 薪资
	private int age; // 年龄
	private String sex; //性别
	
	public Person(String name, int salary, int age,String sex) {
		this.name = name;
		this.salary = salary;
		this.age = age;
		this.sex = sex;
		
	}
	// 省略了get和set
}

1.filter(过滤)

筛选员工中工资高于8000的人,并形成新的集合

List<String> filterList = list.stream().filter(x -> x.getSalary() > 8000).map(Person::getName)
				.collect(Collectors.toList());

2.map和flatMap(映射)

map的使用
将员工的薪资全部增加1000

        List<Person> personListNew = list.stream().map(person -> {
            person.setSalary(person.getSalary() + 1000);
            return person;
        }).collect(Collectors.toList());

flatMap的使用
将两个字符数组合并成一个新的字符数组

List<String> list = Arrays.asList("m,k,l,a", "1,3,5,7");
		List<String> listNew = list.stream().flatMap(s -> {
			// 将每个元素转换成一个stream
			String[] split = s.split(",");
			Stream<String> s2 = Arrays.stream(split);
			return s2;
		}).collect(Collectors.toList());

3.去重、合并、跳过、截取(concat、distinct、skip、limit)

		String[] arr1 = { "a", "b", "c", "d" };
		String[] arr2 = { "d", "e", "f", "g" };
		//创建两个流
		Stream<String> stream1 = Stream.of(arr1);
		Stream<String> stream2 = Stream.of(arr2);
		// concat:合并两个流 
		// distinct:去重
		List<String> newList = Stream.concat(stream1, stream2).distinct().collect(Collectors.toList());
		// limit:限制从流中获得前n个数据
		List<String> collect = stream1.limit(2).collect(Collectors.toList());
		// skip:跳过前n个数据  
		List<String> collect2 = stream2.skip(2).collect(Collectors.toList());

		System.out.println("流合并:" + newList);
		System.out.println("limit:" + collect);
		System.out.println("skip:" + collect2);

4.排序(sorted)

sorted,中间操作。有两种排序:

  • sorted():自然排序,流中元素需实现Comparable接口
  • sorted(Comparator com):Comparator排序器自定义排序
 // 按工资升序排序(自然排序)
List<String> newList = list.stream().sorted(Comparator.comparing(Person::getSalary)).map(Person::getName)
	.collect(Collectors.toList());
// 按工资倒序排序.reversed()
List<String> newList2 = personList.stream().sorted(Comparator.comparing(Person::getSalary).reversed())
	.map(Person::getName).collect(Collectors.toList());
// 先按工资再按年龄升序排序.thenComparing
List<String> newList3 = personList.stream()
			.sorted(Comparator.comparing(Person::getSalary).thenComparing(Person::getAge)).map(Person::getName)
			.collect(Collectors.toList());
// 自定义排序,先按工资再按年龄(降序)
List<String> newList4 = personList.stream().sorted((p1, p2) -> {
		if (p1.getSalary() == p2.getSalary()) {
			return p2.getAge() - p1.getAge();
		} else {
			return p2.getSalary() - p1.getSalary();
		}
		}).map(Person::getName).collect(Collectors.toList());

Stream流的终止(终止操作)

1.聚合(max、min、count)

//获取员工最高工资
Optional<Person> max = list.stream().max(Comparator.comparingInt(Person::getSalary));
//获取员工最低工资
Optional<Person> min= list.stream().min(Comparator.comparingInt(Person::getSalary));
//统计工资大于8000的人数
Long count = list.stream().filter(x -> x.getSalary() > 8000).count();

2.统计(counting、averaging)

Collectors提供了一系列用于数据统计的静态方法:

  • 计数:counting
  • 平均值:averagingInt、averagingLong、averagingDouble
  • 最值:maxBy、minBy
  • 求和:summingInt、summingLong、summingDouble
		// 求总数
		Long count = list.stream().collect(Collectors.counting());
		// 求平均工资
		Double average = list.stream().collect(Collectors.averagingDouble(Person::getSalary));
		// 求最高工资
		Optional<Integer> max = list.stream().map(Person::getSalary).collect(Collectors.maxBy(Integer::compare));
		// 求工资之和
		Integer sum = list.stream().collect(Collectors.summingInt(Person::getSalary));

3. 遍历/匹配(foreach、find、match)

 List<Integer> list = Arrays.asList(7, 6, 9, 3, 8, 2, 1);

       // 遍历输出符合条件的元素
       list.stream().filter(x -> x > 6).forEach(System.out::println);
       // 匹配第一个
       Optional<Integer> findFirst = list.stream().filter(x -> x > 6).findFirst();
       // 匹配任意(适用于并行流)
       Optional<Integer> findAny = list.parallelStream().filter(x -> x > 6).findAny();
       // 是否包含符合特定条件的元素
       boolean anyMatch = list.stream().anyMatch(x -> x > 6);

4.归集collect(toList、toSet、toMap)

List<Integer> listNew = list.stream().filter(x -> x % 2 == 0).collect(Collectors.toList());

Map<?, Person> map = list.stream().filter(p -> p.getSalary() > 8000)
				.collect(Collectors.toMap(Person::getName, p -> p));

5. 分区、分组(partitioningBy、groupingBy)

  • 分区:将stream按条件分为两个Map,比如员工按薪资是否高于8000分为两部分。
  • 分组:将集合分为多个Map,比如员工按性别分组。有单级分组和多级分组。
		// 将员工按薪资是否高于8000分组
       Map<Boolean, List<Person>> part = list.stream().collect(Collectors.partitioningBy(x -> x.getSalary() > 8000));
       // 将员工按性别分组
       Map<String, List<Person>> group = list.stream().collect(Collectors.groupingBy(Person::getSex));
       // 将员工先按性别分组,再按地区分组
       Map<String, Map<String, List<Person>>> group2 = list.stream().collect(Collectors.groupingBy(Person::getSex, Collectors.groupingBy(Person::getArea)));

6. 拼接(joining)

Collectors.joining() 方法以遭遇元素的顺序拼接元素。我们可以传递可选的拼接字符串、前缀和后缀。

 List<String> list = Arrays.asList("1","2","3","4");
 //以空字符拼接,输出 1234
 String result= list.stream().collect(Collectors.joining());
 //以“-”符号拼接,输出1-2-3-4
 String result= list.stream().collect(Collectors.joining("-"));
        System.out.println(result);

多个参数

joining(CharSequence delimiter, CharSequence prefix, CharSequence suffix) 方法接受一个字符串序列作为拼接符,并在拼接完成后添加传递的前缀和后缀。假如我们传递的分隔符为 “-”,前缀为 “[” , 后缀为 “]” 。那么输出结果为 [1-2-3-4]

 List<String> list = Arrays.asList("1","2","3","4");
 String result= list.stream().collect(Collectors.joining("-", "[", "]"));

  • 5
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值