java8中stream流集合的筛选,规约,分组,聚合

简要介绍一下stream

Stream 将要处理的元素集合看作一种流,在流过程中,借助stream api对流中的元素进行操作,比如筛选,排序,聚合等。

创建Stream

List<String> strList = Arrays.asList("a","b","c");

// 创建顺序流
Stream<String> sequenceStream = strList.stream();
sequenceStream.forEach(System.out::println);
log.info("显示效果:");
// a
// b
// c

// 创建并行流
Stream<String> parallelStream = strList.parallelStream();
parallelStream.forEach(System.out::println);

筛选

需求:取出年龄大于10

List<Integer> list = Arrays.asList(6,7,10,19);
Stream<Integer> stream = list.stream();
stream.filter(x -> x>7).forEach(System.out::println);
// 10
// 19

聚合

需求:获取年薪在8w以上用户信息

List<Person> personList = new ArrayList<>();
personList.add(Person.builder().name("Tom").age(10).salary(100000).area("河南").build();
personList.add(Person.builder().name("Jack").age(11).salary(20000).area("广东").build();
personList.add(Person.builder().name("Rose").age(12).salary(10000).area("上海").build();
List<Person) result = personList.stream().filter(item -> item.getSalary() > 80000).collect(Collectors.toList);

需求:获取字符串集合中最长的元素

List<String> strNameList = Arrays.asList("Jack","Rose","Jimss");
Optional<String> maxStr = strNameList.stream().max(Comparator.comparing(String::length));
log.info("获取字符串集合中最长元素:[{}]",maxStr.get());

需求:获取最大值

List<Integer> list = Arrays.asList(7,6,9,4.11,6);
Optional<Integer> max = list.stream().max(Integer::compareTo);
log.info("自然排序最大值:[{}]",max.get()); // 11
Optional<Integer> maxAnother = list.stream().max((o1,o2) -> o2-o1);
log.info("自定义排序:[{}]",maxAnother.get()); // 4

需求:员工薪资最大值

List<Person> personList = new ArrayList<>();
personList.add(Person.builder().name("Tom").age(10).salary(100000).area("河南").build();
personList.add(Person.builder().name("Jack").age(11).salary(20000).area("广东").build();
personList.add(Person.builder().name("Rose").age(12).salary(10000).area("上海").build();
Optional<person> max = personList.stream().max(Comparator.comparingInt(Person::getSalary));
log.info("员工薪资最大值:[{}]",max.get().getSalary()); // 100000

需求:计算Integer集合中大于6的元素的个数

List<Integer> list = Arrays.asList(7,6,9,4,11,6);
long count = list.stream().filter(x -> x > 6).count();
log.info("list中大于6元素个数:[{}]",count); // 3

映射(map/flatMap)

映射,可以将一个流的元素按照一定的映射规则映射到另一个流中。分为map和flatMap:

map:接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素。
flatMap:接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流。
案例一:英文字符串数组的元素全部改为大写。整数数组每个元素+3。

String[] strArr = { "abcd", "bcdd", "defde", "fTr" };
List<String> strList = Arrays.stream(strArr).map(String::toUpperCase).collect(Collectors.toList());

List<Integer> intList = Arrays.asList(1, 3, 5, 7, 9, 11);
List<Integer> intListNew = intList.stream().map(x -> x + 3).collect(Collectors.toList());

System.out.println("每个元素大写:" + strList);
System.out.println("每个元素+3:" + intListNew);


案例二:将员工的薪资全部增加1000。

List<Person> personList = new ArrayList<Person>();
		personList.add(new Person("Tom", 8900, 23, "male", "New York"));
		personList.add(new Person("Jack", 7000, 25, "male", "Washington"));
		personList.add(new Person("Lily", 7800, 21, "female", "Washington"));
		personList.add(new Person("Anni", 8200, 24, "female", "New York"));
		personList.add(new Person("Owen", 9500, 25, "male", "New York"));
		personList.add(new Person("Alisa", 7900, 26, "female", "New York"));

		// 不改变原来员工集合的方式
		List<Person> personListNew = personList.stream().map(person -> {
			Person personNew = new Person(person.getName(), 0, 0, null, null);
			personNew.setSalary(person.getSalary() + 10000);
			return personNew;
		}).collect(Collectors.toList());
		System.out.println("一次改动前:" + personList.get(0).getName() + "-->" + personList.get(0).getSalary());
		System.out.println("一次改动后:" + personListNew.get(0).getName() + "-->" + personListNew.get(0).getSalary());

		// 改变原来员工集合的方式
		List<Person> personListNew2 = personList.stream().map(person -> {
			person.setSalary(person.getSalary() + 10000);
			return person;
		}).collect(Collectors.toList());
		System.out.println("二次改动前:" + personList.get(0).getName() + "-->" + personListNew.get(0).getSalary());
		System.out.println("二次改动后:" + personListNew2.get(0).getName() + "-->" + personListNew.get(0).getSalary());

一次改动前:Tom–>8900
一次改动后:Tom–>18900
二次改动前:Tom–>18900
二次改动后:Tom–>18900

案例三:将两个字符数组合并成一个新的字符数组。

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());

		System.out.println("处理前的集合:" + list);
		System.out.println("处理后的集合:" + listNew);

处理前的集合:[m-k-l-a, 1-3-5]
处理后的集合:[m, k, l, a, 1, 3, 5]

规约

案例一:求Integer集合的元素之和、乘积和最大值。

List<Integer> list = Arrays.asList(1, 3, 2, 8, 11, 4);
		// 求和方式1
		Optional<Integer> sum = list.stream().reduce((x, y) -> x + y);
		// 求和方式2
		Optional<Integer> sum2 = list.stream().reduce(Integer::sum);
		// 求和方式3
		Integer sum3 = list.stream().reduce(0, Integer::sum);
		
		// 求乘积
		Optional<Integer> product = list.stream().reduce((x, y) -> x * y);

		// 求最大值方式1
		Optional<Integer> max = list.stream().reduce((x, y) -> x > y ? x : y);
		// 求最大值写法2
		Integer max2 = list.stream().reduce(1, Integer::max);

		System.out.println("list求和:" + sum.get() + "," + sum2.get() + "," + sum3);
		System.out.println("list求积:" + product.get());
		System.out.println("list求最大值:" + max.get() + "," + max2);

收集

toList,toSet,toMap

下面用一个案例演示toList、toSet和toMap:

List<Integer> list = Arrays.asList(1,6,3,4,6,7,9,6,20);
List<Integer> listNew = list.filter(x -> x%2==0).collect(Collectors.toList());
Set<Integer> set = list.stream().filter(x -> x%2==0).collect(Collectors.toSet());
log.info("toList:[{}]",listNew);
log.info("toSet:[{}]",set);
List<Person> personList = new ArrayList<>();
personList.add(Person.builder().name("Tom").age(10).salary(100000).area("河南").build());
personList.add(Person.builder().name("Jack").age(11).salary(20000).area("广东").build());
personList.add(Person.builder().name("Rose").age(12).salary(10000).area("上海").build());
Map<String,Person> map  = personList.stream().filter(p -> p.getSalary() > 80000).collect(Collectors.toMap(Person::getName,p -> p));
log.info("toMap:[{}]",map);

统计count,averag

  • 计数:count
  • 平均值:averagingInt,averagingLong,averagingDouble
  • 最值:maxBy,minBy
  • 求和:summingInt,summingLong,summingDouble
  • 统计以上所有:summarzingInt,summarzingLong,summarizingDouble
List<Person> personList = new ArrayList<>();
personList.add(Person.builder().name("Tom").age(10).salary(100000).area("河南").build());
personList.add(Person.builder().name("Jack").age(11).salary(20000).area("广东").build());
personList.add(Person.builder().name("Rose").age(12).salary(10000).area("上海").build());
Long count = personList.stream().collect(Collectors.counting());
Double average = personList.stream().collect(Collectors.averagingDouble(Person::getSalary));
Optional<Integer> max = personList.stream().map(Person::getSalary).collect(Collectors.maxBy(Integer::compare));
Integer sum = personList.stream().collect(Collectors.summingInt(Person::getSalary));
DoubleSummaryStatistics collect = personList.stream().collect(Collectors.summarizingDouble(Person::getSalary));
log.info("[员工总数:{}]",count);
log.info("[平均成绩:{}]",average);
log.info("[最高成绩:{}]",max.get());
log.info("[工资总和:{}]",sum);
log.info("[员工所有工资汇总:{}]",collect);

分组(partitioningBy/groupingBy)

分区:将stream按条件分为两个Map,比如员工按薪资是否高于8000分为两部分。
分组:将集合分为多个Map,比如员工按性别分组。有单级分组和多级分组。

List<Person> personList = new ArrayList<>();
personList.add(Person.builder().name("Tom").age(10).salary(100000).area("河南").sex("男").build());
personList.add(Person.builder().name("Jack").age(11).salary(20000).area("广东").sex("女").build());
personList.add(Person.builder().name("Rose").age(12).salary(10000).area("上海").sex("男").build());
// 将员工工资是否大于20000分组
Map<Boolean,List<Person>> sumMap = personList.stream().collect(Collectors.partitioningBy(x -> x.getSalary() > 20000));
log.info("将员工工资是否大于20000分组");
for(Map.Entry<Boolean,List<Person>> item : sumMap.entrySet()){
    log.info("key:[{}],value:[{}]",item.getKey(),item.getValue());
}

// 员工性别分组
Map<String,List<Person>> sexMap = personList.stream().collect(Collectors.groupingBy(Person::getSex));
log.info("员工性别分组");
for(Map.Entry<String,List<Person>> item:sexMap.entrySet()){
     log.info("key:[{}],value:[{}]",item.getKey(),item.getValue());
}

// 先按照性别分组,后按照地区分组
Map<String,Map<String,List<Person>>> multiMap = personList.stream().collect(Collectors.groupingBy(Person::getSex,Collectors.groupingBy(Person::getArea)));
log.info("先按照性别分组,后按照地区分组");
for(Map.Entry<String,Map<String,List<Person>>> item:sexMap.entrySet()){
     log.info("key:[{}],value:[{}]",item.getKey(),item.getValue());
}

接合

List<Person> personList = new ArrayList<>();
personList.add(Person.builder().name("Tom").age(10).salary(100000).area("河南").sex("男").build());
personList.add(Person.builder().name("Jack").age(11).salary(20000).area("广东").sex("女").build());
personList.add(Person.builder().name("Rose").age(12).salary(10000).area("上海").sex("男").build());
String nameStr = personList.stream().map(p->p.getName()).collect(Collectors.joining("*"));
log.info("[所有员工姓名:{}]",nameStr);

排序

// 年龄升序
List<String> result = personList.stream().sorted(Comparator.comparing(Person::getAge)).map(Person::getName).collect(Collectors.toList());

// 年龄降序
List<String> result = personList.stream().sorted(Comparator.comparing(Person::getAge).reversed()).map(Person::getName).collect(Collectors.toList());

提取,组合

String[] arrFirst = {"a","b","c","d"};
String[] arSecond = {"d","e","f","g"};
Stream<String> arrFirstStream = Stream.of(arrFirst);
Stream<String> arrSecondStream = Stream.of(arrSecod);
log.info("合并流,去重");
List<String> listFirst = Stream.concat(arrFirstStream,arrSecondStream)
.distinct().collect(Collectors.toList());
List<String> listSecond = Stream.iterate(1,x->x+2).limit(10).collect(Collectors.toList());
List<String> listThird = Stream.iterate(1,x->x+20)
.skip(1).limit(5).collect(Collectors.toList());
log.info("listFirst:[{}]",listFirst);
log.info("listSecond :[{}]",listSecond );
log.info("listThird :[{}]",listThird );

你可能感兴趣的:(java,开发语言)