目录

一  了解Stream

1 Stream概述

那么什么是Stream?

Stream可以由数组或集合创建

Stream有几个特性:

Stream流的起始操作

2 Stream的创建----Stream可以通过集合数组创建。

3、通过 java.util.Collection.stream() 方法 用map集合 ,间接创建生成流

stream和parallelStream的简单区分:

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

3 Stream的使用

类声明

类方法   注意: 这些方法是从 java.lang.Object 类继承来的。

Optional 实例

输出结果:

案例使用的员工类

3.1 遍历/匹配(foreach/find/match)

foreach()是终止操作,只能执行一次,之后再执行此操作,会报IllegalStateException异常

案例--- forEach() /  findFirst() /  findAny() / findFirst.get() / findAny.get() / anyMatch()

二 Stream流常见的中间操作

3.2 筛选(filter)--进行筛选提取,不对元素进行修改附加操作

案例一:filter的常规中间操作

案例二:筛选出Integer集合中大于7的元素,并打印出来

案例三: 筛选员工中工资高于8000的人,并形成新的集合。 形成新集合依赖collect(收集)。

3.3 聚合(max/min/count)

3.4 映射(map/flatMap)--会对每一个元素进行修改等附加操作

3.5 归约(reduce)

3.6 收集(collect)

3.6.1 归集(toList/toSet/toMap)

toMap 的案例

3.6.2 统计(count/averaging)

3.6.3 分组(partitioningBy/groupingBy)

3.6.4 接合(joining)

3.6.5 归约(reducing)

3.7 排序(sorted)---自然排序调用的是equals()方法

3.8 提取/组合--中间操作


一  了解Stream

1 Stream概述

Java 8 是一个非常成功的版本,这个版本新增的Stream,配合同版本出现的 Lambda ,给我们操作集合(Collection)提供了极大的便利。

那么什么是Stream?

Stream将要处理的元素集合看作一种流,在流的过程中,借助Stream API对流中的元素进行操作,比如:筛选、映射、排序、归约、分组、聚合、提取与组合、收集、接合、foreach遍历等。

Stream可以由数组或集合创建

对流的操作分为两种:

中间操作:每次返回一个新的流,可以有多个。

终止操作:流只能进行一次终端操作,终止操作结束后流无法再次使用。终止操作会产生一个新的集合或值。

Stream有几个特性:

stream不存储数据,而是按照特定的规则对数据进行计算,一般会输出结果。

stream不会改变数据源,通常情况下会产生一个新的集合或一个值。

stream具有延迟执行特性,只有调用终端操作时,中间操作才会执行。

Stream流的起始操作

2 Stream的创建----Stream可以通过集合数组创建。

1、通过 java.util.Collection.stream() 方法 用list集合 创建流 --顺序流/并行流

     /** @Author Vincent* @Description* 1、通过 java.util.Collection.stream() 方法用集合创建流**/List<String> list = Arrays.asList("A", "B", "C");//创建一个顺序流Stream<String> stream = list.stream();stream.forEach(System.out::println);System.out.println("=============list.stream()=================");
//创建一个并行流Stream<String> parallelStream = list.parallelStream();parallelStream.forEach(System.out::println);System.out.println("===============list.parallelStream()===============");

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

System.out.println("============set.stream()==================");HashSet<String> set = new HashSet<>();set.add("法外狂徒张三");set.add("芜湖大司马");set.add("杭州吴彦祖");Stream<String> setStream = set.stream();setStream.forEach(System.out::println);

输出结果:

============set.stream()==================
法外狂徒张三
芜湖大司马
杭州吴彦祖

3、通过 java.util.Collection.stream() 方法 用map集合 ,间接创建生成流

System.out.println("============Map集合只能间接生成流==================");System.out.println("===========map.keySet().stream()================");HashMap<String, Integer> map = new HashMap<>();map.put("唐伯虎",9527);map.put("祝枝山",9528);map.put("文征明",9529);map.put("徐祯卿",9530);Stream<String> keyStream = map.keySet().stream();keyStream.forEach(System.out::println);System.out.println("===========map.values().stream()================");Stream<Integer> valueStream = map.values().stream();valueStream.forEach(System.out::println);System.out.println("============map.entrySet().stream()============");Stream<Map.Entry<String, Integer>> entryStream= map.entrySet().stream();entryStream.forEach(System.out::println);

输出结果:

============Map集合只能间接生成流==================
===========map.keySet().stream()================
祝枝山
徐祯卿
唐伯虎
文征明
===========map.values().stream()================
9528
9530
9527
9529
============map.entrySet().stream()============
祝枝山=9528
徐祯卿=9530
唐伯虎=9527
文征明=9529

stream和parallelStream的简单区分:

stream是顺序流,由主线程按顺序对流执行操作;

而parallelStream是并行流,内部以多线程并行执行的方式对流进行操作;

前提是流中的数据处理没有顺序要求。例如筛选集合中的奇数,两者的处理不同之处:

如果流中的数据量足够大,并行流可以加快处速度。

除了直接创建并行流,还可以通过parallel()把顺序流转换成并行流:

List<Integer> list2 = Arrays.asList(3, 4, 5,7,9,8,1,18);//把顺序流转成并行流   过滤x>6的数,取第一个数Optional<Integer> integergOptional = list2.stream().parallel().filter(x -> x > 6).findFirst();System.out.println(stringOptional);System.out.println("==============================");

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

/*** @Author Vincent* @Description //TODO* 2、使用java.util.Arrays.stream(T[] array)方法用数组创建流**/int[] array ={2,4,6,8,9};IntStream arrStream = Arrays.stream(array);arrStream.forEach(System.out::println);System.out.println("===============Arrays.stream()===============");

4.1 使用Stream的静态方法:of()、iterate()、generate()

 /*** @Author Vincent* @Description* 3、使用Stream的静态方法:of()、iterate()、generate()**/System.out.println("==============Stream.of()================");//of()Stream<int[]> arrayStream = Stream.of(array);Stream<Integer> integerStream = Stream.of(1, 2, 3, 4, 5, 6);Stream<String> stringStream = Stream.of("hello", "world", "java", "yyds");arrayStream.forEach(System.out::println);integerStream.forEach(System.out::println);stringStream.forEach(System.out::println);System.out.println("==============Stream.iterate()================");//iterate() x从0开始,进行x+3运算,取前4条数据Stream<Integer> limitStream = Stream.iterate(0, (x) -> x + 3).limit(4);//foreach结合方法引用limitStream.forEach(System.out::println);System.out.println("==============Stream.generate()================");//generate() 生成Stream<Double> generateStream = Stream.generate(Math::random).limit(3);generateStream.forEach(System.out::println);

输出结果:

============list.stream()==================
A
B
C
============set.stream()==================
法外狂徒张三
芜湖大司马
杭州吴彦祖
============Map集合只能间接生成流==================
===========map.keySet().stream()================
祝枝山
徐祯卿
唐伯虎
文征明
===========map.values().stream()================
9528
9530
9527
9529
============map.entrySet().stream()============
祝枝山=9528
徐祯卿=9530
唐伯虎=9527
文征明=9529
=============list2.stream().parallel()=================
Optional[7]
=============list.parallelStream()=================
B
C
A
=============Arrays.stream()=================
2
4
6
8
9
==============Stream.of()================
[I@643b1d11
1
2
3
4
5
6
hello
world
java
yyds
==============Stream.iterate()================
0
3
6
9
==============Stream.generate()================
0.8949224931186376
0.3844974833341598
0.7886508926329633Process finished with exit code 0

3 Stream的使用

在使用stream之前,先理解一个概念:Optional

Optional 类是一个可以为null的容器对象。如果值存在则isPresent()方法会返回true,调用get()方法会返回该对象。

Optional 是个容器:它可以保存类型T的值,或者仅仅保存null。Optional提供很多有用的方法,这样我们就不用显式进行空值检测。

Optional 类的引入很好的解决空指针异常。

类声明

以下是一个 java.util.Optional<T> 类的声明:

public final class Optional<T> extends Object

类方法   注意: 这些方法是从 java.lang.Object 类继承来的。

序号

方法 & 描述

1

static <T> Optional<T> empty()

返回空的 Optional 实例。

2

boolean equals(Object obj)

判断其他对象是否等于 Optional。

3

Optional<T> filter(Predicate<? super <T> predicate)

如果值存在,并且这个值匹配给定的 predicate,返回一个Optional用以描述这个值,否则返回一个空的Optional。

4

<U> Optional<U> flatMap(Function<? super T,Optional<U>> mapper)

如果值存在,返回基于Optional包含的映射方法的值,否则返回一个空的Optional

5

T get()

如果在这个Optional中包含这个值,返回值,否则抛出异常:NoSuchElementException

6

int hashCode()

返回存在值的哈希码,如果值不存在 返回 0。

7

void ifPresent(Consumer<? super T> consumer)

如果值存在则使用该值调用 consumer , 否则不做任何事情。

8

boolean isPresent()

如果值存在则方法会返回true,否则返回 false。

9

<U>Optional<U> map(Function<? super T,? extends U> mapper)

如果有值,则对其执行调用映射函数得到返回值。如果返回值不为 null,则创建包含映射返回值的Optional作为map方法返回值,否则返回空Optional。

10

static <T> Optional<T> of(T value)

返回一个指定非null值的Optional。

11

static <T> Optional<T> ofNullable(T value)

如果为非空,返回 Optional 描述的指定值,否则返回空的 Optional。

12

T orElse(T other)

如果存在该值,返回值, 否则返回 other。

13

T orElseGet(Supplier<? extends T> other)

如果存在该值,返回值, 否则触发 other,并返回 other 调用的结果。

14

<X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier)

如果存在该值,返回包含的值,否则抛出由 Supplier 继承的异常

15

String toString()

返回一个Optional的非空字符串,用来调试

Optional 实例

/*** @author Vincent* @version V1.0* @Package com.legion.streamstudy* @Description Java8-->Optional的学习* @date 2022/2/26 14:33**/public class OptionalTest {public static void main(String[] args) {//创建类对象OptionalTest java8Test = new OptionalTest();Integer value1 = null;Integer value2 = new Integer(10);// Optional.ofNullable - 允许传递为 null 参数Optional<Integer> a = Optional.ofNullable(value1);// Optional.of - 如果传递的参数是 null,抛出异常 NullPointerExceptionOptional<Integer> b = Optional.of(value2);System.out.println(java8Test.sum(a,b));}public Integer sum(Optional<Integer> a, Optional<Integer> b){// Optional.isPresent - 判断值是否存在System.out.println("第一个参数值存在: " + a.isPresent());System.out.println("第二个参数值存在: " + b.isPresent());// Optional.orElse - 如果值存在,返回它,否则返回默认值Integer value1 = a.orElse(new Integer(0));//Optional.get() - 获取值,值需要存在Integer value2 = b.get();return value1 + value2;}}

输出结果:

第一个参数值存在: false
第二个参数值存在: true
10Process finished with exit code 0

案例使用的员工类

这是后面案例中使用的员工类:

/*** @author Vincent* @version V1.0* @Package com.legion.streamstudy.exampleDemo* @Description 员工类* @date 2022/2/26 14:49**/public class Person {private String name;  // 姓名private int salary; // 薪资private int age; // 年龄private String sex; //性别private String area;  // 地区public Person() { }public Person(String name, int salary, int age, String sex, String area) {this.name = name;this.salary = salary;this.age = age;this.sex = sex;this.area = area;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getSalary() {return salary;}public void setSalary(int salary) {this.salary = salary;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public String getSex() {return sex;}public void setSex(String sex) {this.sex = sex;}public String getArea() {return area;}public void setArea(String area) {this.area = area;}@Overridepublic boolean equals(Object o) {if (this == o) {return true;}if (o == null || getClass() != o.getClass()) {return false;}Person person = (Person) o;return salary == person.salary &&age == person.age &&Objects.equals(name, person.name) &&Objects.equals(sex, person.sex) &&Objects.equals(area, person.area);}@Overridepublic int hashCode() {return Objects.hash(name, salary, age, sex, area);}@Overridepublic String toString() {return "Person{" +"name='" + name + '\'' +", salary=" + salary +", age=" + age +", sex='" + sex + '\'' +", area='" + area + '\'' +'}';}
}

3.1 遍历/匹配(foreach/find/match)

foreach()是终止操作,只能执行一次,之后再执行此操作,会报IllegalStateException异常

Stream也是支持类似集合的遍历和匹配元素的,只是Stream中的元素是以Optional类型存在的。Stream的遍历、匹配非常简单。

 案例--- forEach() /  findFirst() /  findAny() / findFirst.get() / findAny.get() / anyMatch()

public class StreamForeachTest {public static void main(String[] args) {List<Integer> list = Arrays.asList(7, 6, 9, 3, 8, 2, 1);/*** @Author Vincent* @Description 遍历输出符合条件的元素* list.stream() 调用stream流方法* filter(x->x>6) 筛选过滤条件* forEach()遍历* (System.out::println) 方法引用***/list.stream().filter(x -> x > 6).forEach(System.out::println);/* 匹配满足条件的第一个元素* findFirst()* */Optional<Integer> findFirst = list.stream().filter(x -> x > 6).findFirst();/* 匹配任意(适用于并行流)* findAny()* */Optional<Integer> findAny = list.parallelStream().filter(x -> x > 6).findAny();boolean anyMatch = list.stream().anyMatch(x -> x > 6);System.out.println("匹配满足条件的第一个值:" + findFirst.get());System.out.println("匹配满足条件的任意一个值:" + findAny.get());System.out.println("是否存在大于6的值:" + anyMatch);}}

输出结果:

7
9
8
匹配满足条件的第一个值:7
匹配满足条件的任意一个值:8
是否存在大于6的值:trueProcess finished with exit code 0

二 Stream流常见的中间操作

3.2 筛选(filter)--进行筛选提取,不对元素进行修改附加操作

筛选,是按照一定的规则校验流中的元素,将符合条件的元素提取到新的流中的操作。

案例一:filter的常规中间操作

public class StreamFilterTest {public static void main(String[] args) {//把集合长度为3的元素在控制台输出ArrayList<String> list1 = new ArrayList<>();list1.add("林青霞");list1.add("王祖贤");list1.add("张曼玉");list1.add("张敏");list1.add("钟丽缇");list1.add("朱茵");list1.add("莫文蔚");//把list集合中以朱开头的元素输出list1.stream().filter(s->s.startsWith("朱")).forEach(System.out::println);System.out.println("--------");//把集合长度为3的元素在控制台输出list1.stream().filter(s->s.length()==3).forEach(System.out::println);System.out.println("--------");//把list集合中以张开头且长度为3的元素在控制台输出list1.stream().filter(s->s.startsWith("张")).filter(s->s.length()==3).forEach(System.out::println);}
}

输出结果:

朱茵
--------
林青霞
王祖贤
张曼玉
钟丽缇
莫文蔚
--------
张曼玉Process finished with exit code 0

案例二:筛选出Integer集合中大于7的元素,并打印出来

public class StreamFilterTest {public static void main(String[] args) {//筛选出Integer集合中大于7的元素,并打印出来List<Integer> list = Arrays.asList(6, 7, 3, 8, 1, 2, 9);Stream<Integer> stream = list.stream();stream.filter(x -> x > 7).forEach(System.out::println);}
}

输出结果:

8
9Process finished with exit code 0

案例三: 筛选员工中工资高于8000的人,并形成新的集合。 形成新集合依赖collect(收集)。

/*** @author Vincent* @version V1.0* @Package com.legion.streamstudy.exampleDemo* @Description 筛选员工中工资高于8000的人,并形成新的集合* @date 2022/2/26 15:24**/public class StreamFilterCollect {public static void main(String[] args) {//多态List<Person> list = new ArrayList<>();list.add(new Person("Tom", 8900, 23, "male", "New York"));list.add(new Person("Jack", 7000, 25, "male", "Washington"));list.add(new Person("Lily", 7800, 21, "female", "Washington"));list.add(new Person("Anni", 8200, 24, "female", "New York"));list.add(new Person("Owen", 9500, 25, "male", "New York"));list.add(new Person("Alisa", 7900, 26, "female", "New York"));/*** @Author Vincent* @Description 筛选员工中工资高于8000的人,并形成新的集合。 形成新集合依赖collect(收集)* @Date 15:33 2022/2/26* list.stream() 调用stream流* filter(person->person.getSalary()>8000) 筛选薪水>8000的person   如<Tom,8900>,<Anni,8200>,<Owen,9500>* map(Person::getName) 把满足上述条件的人的人名获取到放在map中* collect(Collectors.toList()) 收集转成list集合* forEach(System.out::println) 遍历输出**/list.stream().filter(person->person.getSalary()>8000).map(Person::getName).collect(Collectors.toList()).forEach(System.out::println);}
}

输出结果:

Tom
Anni
OwenProcess finished with exit code 0

3.3 聚合(max/min/count)

maxmincount这些字眼你一定不陌生,没错,在mysql中我们常用它们进行数据统计。

Java stream中也引入了这些概念和用法,极大地方便了我们对集合、数组的数据统计工作。

案例一:获取String集合中最长的元素。

/*** @author Vincent* @version V1.0* @Package com.legion.streamstudy.exampleDemo* @Description TODO* @date 2022/2/26 15:54**/
public class StreamAggregateTest {public static void main(String[] args) {/*** @Author Vincent* @Description //获取String集合中最长的元素* @Date 15:58 2022/2/26* max()* Comparator.comparing(String::length) 调用比较器中的comparing()方法,比较String类型的元素长度* get()方法,如果值存在则返回,值不存在则抛出异常NoSuchElementException**/List<String> list = Arrays.asList("adnm", "admmt", "csdn", "xbangd", "hellolegion");Optional<String> maxLength = list.stream().max(Comparator.comparing(String::length));System.out.println("最长的字符串:" + maxLength.get());}
}

输出结果:

最长的字符串:hellolegion

案例二:获取Integer集合中的最大值。

public class MaxIntegerTest {public static void main(String[] args) {List<Integer> list = Arrays.asList(7, 6, 9, 4, 11, 6);// 自然排序Optional<Integer> maxInteger = list.stream().max(Integer::compareTo);/*** @Author Vincent* @Description  自定义排序---要创建比较器对象--调用compare()方法* return o1.compareTo(o2);* new Comparator<Integer>() {} 匿名内部类* get()方法,如果值存在则返回,值不存在则抛出异常NoSuchElementException * @Date 16:25 2022/1/26**/Optional<Integer> maxInteger2 = list.stream().max(new Comparator<Integer>() {@Overridepublic int compare(Integer o1, Integer o2) {return o1.compareTo(o2);}});System.out.println("自然排序的最大值:" + maxInteger.get());System.out.println("自定义排序的最大值:" + maxInteger2.get());}
}

输出结果:

自然排序的最大值:11
自定义排序的最大值:11Process finished with exit code 0

案例三:获取员工工资最高的人。

public class MaxSalaryTest {public static void main(String[] args) {//案例三:获取员工工资最高的人List<Person> list = new ArrayList<>();list.add(new Person("Tom", 8900, 23, "male", "New York"));list.add(new Person("Jack", 7000, 25, "male", "Washington"));list.add(new Person("Lily", 7800, 21, "female", "Washington"));list.add(new Person("Anni", 8200, 24, "female", "New York"));list.add(new Person("Owen", 9500, 25, "male", "New York"));list.add(new Person("Alisa", 7900, 26, "female", "New York"));Optional<Person> maxSalary = list.stream().max(Comparator.comparingInt(Person::getSalary));System.out.println("员工工资最大值:" + maxSalary.get().getSalary());}
}

输出结果:

员工工资最大值:9500

案例四:计算Integer集合中大于6的元素的个数。

public class MaxCountTest {public static void main(String[] args) {List<Integer> list = Arrays.asList(7, 6, 4, 8, 2, 11, 9);long count = list.stream().filter(x -> x > 6).count();System.out.println("list中大于6的元素个数:" + count);}
}

输出结果:

list中大于6的元素个数:4

3.4 映射(map/flatMap)--会对每一个元素进行修改等附加操作

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

  • map:接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素。
  • flatMap:接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流。

案例一:英文字符串数组的元素全部改为大写。整数数组每个元素+3。

public class MapCollectTest {public static void main(String[] args) {/*** @Author Vincent* map:接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素。**///英文字符串数组的元素全部改为大写String[] strArr = {"abcd", "bcdd", "defde", "fTr"};List<String> stringList = Arrays.stream(strArr).map(String::toUpperCase).collect(Collectors.toList());//整数数组每个元素+3List<Integer> integerList = Arrays.asList(1, 3, 5, 7, 9, 11);List<Integer> integerListNew = integerList.stream().map(x -> x + 3).collect(Collectors.toList());System.out.println("每个元素大写:" + stringList);System.out.println("每个元素+3:" + integerListNew);}
}

输出结果:

每个元素大写:[ABCD, BCDD, DEFDE, FTR]
每个元素+3:[4, 6, 8, 10, 12, 14]Process finished with exit code 0

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

public class MapCollectTest2 {public static void main(String[] args) {//案例二:将员工的薪资全部增加1000。List<Person> list = new ArrayList<>();list.add(new Person("Tom", 8900, 23, "male", "New York"));list.add(new Person("Jack", 7000, 25, "male", "Washington"));list.add(new Person("Lily", 7800, 21, "female", "Washington"));list.add(new Person("Anni", 8200, 24, "female", "New York"));list.add(new Person("Owen", 9500, 25, "male", "New York"));list.add(new Person("Alisa", 7900, 26, "female", "New York"));//1.不改变原来员工集合的方式List<Person> personListNew = list.stream().map(person -> {Person personNew = new Person(person.getName(), 0, 0, null, null);personNew.setSalary(person.getSalary() + 1000);return personNew;}).collect(Collectors.toList());// Person person = list.get(0);System.out.println("一次改动前:" + list.get(0).getName() + "-->" + list.get(0).getSalary());System.out.println("一次改动后:" + personListNew.get(0).getName() + "-->" + personListNew.get(0).getSalary());//2.改变原来员工集合的方式List<Person> personListNew2 = list.stream().map(person -> {person.setSalary(person.getSalary() + 10000);return person;}).collect(Collectors.toList());System.out.println("二次改动前:" + personListNew.get(0).getName() + "-->" + personListNew.get(0).getSalary());System.out.println("二次改动后:" + personListNew2.get(0).getName() + "-->" + personListNew2.get(0).getSalary());}
}

输出结果:

一次改动前:Tom-->8900

一次改动后:Tom-->9900

二次改动前:Tom-->9900

二次改动后:Tom-->18900

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

public class MapCollectTest3 {public static void main(String[] args) {//将两个字符数组合并成一个新的字符数组。List<String> list = Arrays.asList("m,k,l,a", "1,3,5,7");List<String> listNew = list.stream().flatMap(s -> {// 将每个元素转换成一个streamString[] 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,7]
处理后的集合:[m-k-l-a, 1, 3, 5, 7]

3.5 归约(reduce)

归约,也称缩减,顾名思义,是把一个流缩减成一个值,能实现对集合 求和、求乘积 和求最值 操作。

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

public class ReduceTest2 {public static void main(String[] args) {// 求所有员工的工资之和和最高工资。List<Person> list = new ArrayList<>();list.add(new Person("Tom", 8900, 23, "male", "New York"));list.add(new Person("Jack", 7000, 25, "male", "Washington"));list.add(new Person("Lily", 7800, 21, "female", "Washington"));list.add(new Person("Anni", 8200, 24, "female", "New York"));list.add(new Person("Owen", 9500, 25, "male", "New York"));list.add(new Person("Alisa", 7900, 26, "female", "New York"));// 求工资之和方式1--sumOptional<Integer> sumSalary = list.stream().map(Person::getSalary).reduce(Integer::sum);// 求工资之和方式2Integer sumSalary2 = list.stream().map(Person::getSalary).reduce(0, Integer::sum);//求工资之和方式3Integer sumSalary3 = list.stream().reduce(0, (sum, p) -> sum += p.getSalary(), (sum1, sum2) -> sum1 + sum2);//求工资之和方式4Integer sumSalary4 = list.stream().reduce(0, (sum, p) -> sum += p.getSalary(), Integer::sum);//求最高工资方式1--maxInteger maxSalary  = list.stream().reduce(0, (max, p) -> max > p.getSalary() ? max : p.getSalary(), Integer::max);//求最高工资方式2Integer maxSalary2 = list.stream().reduce(0, (max, p) -> max > p.getSalary() ? max : p.getSalary(),(max1, max2) -> max1 > max2 ? max1 : max2);System.out.println("工资之和:" + sumSalary.get() + "," + sumSalary2 + "," + sumSalary3+","+sumSalary4);System.out.println("最高工资:" + maxSalary + "," + maxSalary2);}
}

输出结果:

list求和:29,29,29
list求积:2112
list求最大值:11,11

案例二:求所有员工的工资之和和最高工资。

/*** @author Vincent* @version V1.0* @Package com.legion.streamstudy.exampleDemo.streamReduce* @Description 案例二:求所有员工的工资之和和最高工资。* @date 2022/2/26 19:24**/public class ReduceTest2 {public static void main(String[] args) {// 求所有员工的工资之和和最高工资。List<Person> list = new ArrayList<>();list.add(new Person("Tom", 8900, 23, "male", "New York"));list.add(new Person("Jack", 7000, 25, "male", "Washington"));list.add(new Person("Lily", 7800, 21, "female", "Washington"));list.add(new Person("Anni", 8200, 24, "female", "New York"));list.add(new Person("Owen", 9500, 25, "male", "New York"));list.add(new Person("Alisa", 7900, 26, "female", "New York"));// 求工资之和方式1--sumOptional<Integer> sumSalary = list.stream().map(Person::getSalary).reduce(Integer::sum);//求工资之和方式2Integer sumSalary2 = list.stream().reduce(0, (sum, p) -> sum += p.getSalary(), (sum1, sum2) -> sum1 + sum2);//求工资之和方式3Integer sumSalary3 = list.stream().reduce(0, (sum, p) -> sum += p.getSalary(), Integer::sum);//求最高工资方式1--maxInteger maxSalary  = list.stream().reduce(0, (max, p) -> max > p.getSalary() ? max : p.getSalary(), Integer::max);//求最高工资方式2Integer maxSalary2 = list.stream().reduce(0, (max, p) -> max > p.getSalary() ? max : p.getSalary(),(max1, max2) -> max1 > max2 ? max1 : max2);System.out.println("工资之和:" + sumSalary.get() + "," + sumSalary2 + "," + sumSalary3);System.out.println("最高工资:" + maxSalary + "," + maxSalary2);}
}

输出结果:

工资之和:49300,49300,49300,49300
最高工资:9500,9500Process finished with exit code 0

3.6 收集(collect)

collect,收集,可以说是内容最繁多、功能最丰富的部分了。

从字面上去理解,就是把一个流收集起来,最终 可以是收集成一个值 也 可以收集成一个新的集合。

collect主要依赖java.util.stream.Collectors类内置的静态方法

3.6.1 归集(toList/toSet/toMap)

因为流不存储数据,那么在流中的数据完成处理后,需要将流中的数据重新归集到新的集合里。

toList、toSet和toMap比较常用,另外还有toCollection、toConcurrentMap等复杂一些的用法。

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

public class StreamCollectTest {public static void main(String[] args) {//归集(toList/toSet/toMap)List<Integer> list = Arrays.asList(1, 6, 3, 4, 6, 7, 9, 6, 20);//筛选偶数转成list集合List<Integer> listNew = list.stream().filter(x -> x % 2 == 0).collect(Collectors.toList());//筛选偶数转成set(无序且不重复的)集合Set<Integer> set = list.stream().filter(x -> x % 2 == 0).collect(Collectors.toSet());List<Person> personList = new ArrayList<>();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"));//筛选出薪水>8000的人,转成map集合Map<String, Person> map = personList.stream().filter(p -> p.getSalary() > 8000).collect(Collectors.toMap(Person::getName, P -> P));System.out.println("toList:" + listNew);System.out.println("toSet:" + set);System.out.println("toMap:" + map);}
}

输出结果:

toList:[6, 4, 6, 6, 20]
toSet:[4, 20, 6]
toMap:{Tom=com.legion.streamstudy.exampleDemo.Person@6b2fad11, Anni=com.legion.streamstudy.exampleDemo.Person@79698539}Process finished with exit code 0

toMap 的案例

public class MapCollectTest4 {public static void main(String[] args) {//创建list集合ArrayList<String> list = new ArrayList<>();list.add("林青霞");list.add("王祖贤");list.add("钟丽缇");list.add("张敏");list.add("朱茵");list.add("莫文蔚");//得到3个字的流Stream<String> listStream = list.stream().filter(s -> s.length() == 3);//把Stream流操作玩的数据收集到list集合中List<String> names = listStream.collect(Collectors.toList());//names.forEach(System.out::println);//创建set集合HashSet<Integer> set = new HashSet<>();set.add(10);set.add(20);set.add(30);set.add(35);//得到元素大于25的流Stream<Integer> ages = set.stream().filter(age -> age > 25);//把ages 收集到Set集合中,并遍历//ages.collect(Collectors.toSet()).forEach(System.out::println);System.out.println("==============Collectors.toMap()=====================");//定义一个字符串数组,每一个字符串数据由姓名数据和年龄数据组成String[] strArray = {"林青霞,30", "王祖贤,25", "钟丽缇,24", "张敏,26", "朱茵,27", "莫文蔚,28"};//得到字符串年龄数据大于28的流Stream<String> ageStream = Stream.of(strArray).filter(s -> Integer.parseInt(s.split(",")[1]) > 25);//把使用Stream流操作的数据收集到Map集合中遍历,姓名作为key,年龄作为valueMap<String, Integer> map = ageStream.collect(Collectors.toMap(s -> s.split(",")[0],s -> Integer.parseInt(s.split(",")[1])));Set<String> keySet = map.keySet();for (String key : keySet) {Integer value = map.get(key);System.out.println(key + "," + value);}}
}

输出结果:

林青霞,30
张敏,26
莫文蔚,28
朱茵,27Process finished with exit code 0

3.6.2 统计(count/averaging)

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

  • 计数:count
  • 平均值:averagingIntaveragingLongaveragingDouble
  • 最值:maxByminBy
  • 求和:summingIntsummingLongsummingDouble
  • 统计以上所有:summarizingIntsummarizingLongsummarizingDouble

案例:统计员工人数、平均工资、工资总额、最高工资。

数据统计常用Collectors类对象来调用各种方法

public class CountAverageTest {public static void main(String[] args) {//统计员工人数、平均工资、工资总额、最高工资。List<Person> list = new ArrayList<>();list.add(new Person("Tom", 8900, 23, "male", "New York"));list.add(new Person("Jack", 7000, 25, "male", "Washington"));list.add(new Person("Lily", 7800, 21, "female", "Washington"));// 求总数方式1Long count = list.stream().collect(Collectors.counting());// 求总数方式2Long count2 = list.stream().count();// 求总数方式3Long count3 = (long) list.size();// 求平均工资Double average  = list.stream().collect(Collectors.averagingDouble(Person::getSalary));// 求最高工资方式1Integer max1 = list.stream().reduce(0, (max, p) -> max > p.getSalary() ? max : p.getSalary(),Integer::max);// 求最高工资方式2Optional<Integer> max2 = list.stream().map(Person::getSalary).collect(Collectors.maxBy(Integer::compareTo));// 求最高工资方式3Optional<Integer> max3 = list.stream().map(Person::getSalary).max(Integer::compareTo);// 求工资之和IntSummaryStatistics sum = list.stream().collect(Collectors.summarizingInt(Person::getSalary));// 一次性统计所有信息DoubleSummaryStatistics statistics = list.stream().collect(Collectors.summarizingDouble(Person::getSalary));System.out.println("员工总数:" + count+","+count2+","+count3);System.out.println("员工平均工资:" + average);System.out.println("员工最高工资:" + max1+","+max2.get()+","+max3.get());System.out.println("员工工资总和:" + sum.getSum());System.out.println("员工工资所有统计:" + statistics);}
}

输出结果:

员工总数:3,3,3
员工平均工资:7900.0
员工最高工资:8900,8900,8900
员工工资总和:23700
员工工资所有统计:DoubleSummaryStatistics{count=3, sum=23700.000000, min=7000.000000, average=7900.000000, max=8900.000000}Process finished with exit code 0

3.6.3 分组(partitioningBy/groupingBy)

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

案例:将员工按薪资是否高于8000分为两部分--partitioningBy() ;将员工按性别和地区分组--groupingBy()

public class GroupByTest {public static void main(String[] args) {//将员工按薪资是否高于8000分为两部分;将员工按性别和地区分组List<Person> list = new ArrayList<>();list.add(new Person("Tom", 8900,23, "male", "New York"));list.add(new Person("Jack", 7000,25, "male", "Washington"));list.add(new Person("Lily", 7800,28, "female", "Washington"));list.add(new Person("Anni", 8200,19, "female", "New York"));list.add(new Person("Owen", 9500,26, "male", "New York"));list.add(new Person("Alisa", 7900,21, "female", "New York"));// 将员工按薪资 是否 高于8000分组(两部分:高于8000和低于8000)--partitioningBy()Map<Boolean, List<Person>> part = list.stream().collect(Collectors.partitioningBy(x -> x.getSalary() > 8000));// 将员工按性别分组--groupingBy()Map<String, List<Person>> group  = list.stream().collect(Collectors.groupingBy(Person::getSex));// 将员工先按性别分组,再按地区分组--groupingBy()Map<String, Map<String, List<Person>>> group2  = list.stream().collect(Collectors.groupingBy(Person::getSex, Collectors.groupingBy(Person::getArea)));System.out.println("员工按薪资是否大于8000分组情况:" + part);System.out.println("员工按性别分组情况:" + group);System.out.println("员工按性别、地区:" + group2);}
}

输出结果:

员工按薪资是否大于8000分组情况:
{ false=[com.legion.streamstudy.exampleDemo.Person@42d3bd8b, com.legion.streamstudy.exampleDemo.Person@26ba2a48, com.legion.streamstudy.exampleDemo.Person@5f2050f6],true=[com.legion.streamstudy.exampleDemo.Person@3b81a1bc, com.legion.streamstudy.exampleDemo.Person@64616ca2, com.legion.streamstudy.exampleDemo.Person@13fee20c] }员工按性别分组情况:
{ female=[com.legion.streamstudy.exampleDemo.Person@26ba2a48, com.legion.streamstudy.exampleDemo.Person@64616ca2, com.legion.streamstudy.exampleDemo.Person@5f2050f6],male=[com.legion.streamstudy.exampleDemo.Person@3b81a1bc, com.legion.streamstudy.exampleDemo.Person@42d3bd8b, com.legion.streamstudy.exampleDemo.Person@13fee20c] }员工按性别、地区:
{ female={ New York=[com.legion.streamstudy.exampleDemo.Person@64616ca2, com.legion.streamstudy.exampleDemo.Person@5f2050f6], Washington=[com.legion.streamstudy.exampleDemo.Person@26ba2a48]},male={ New York=[com.legion.streamstudy.exampleDemo.Person@3b81a1bc, com.legion.streamstudy.exampleDemo.Person@13fee20c],  Washington=[com.legion.streamstudy.exampleDemo.Person@42d3bd8b]} }Process finished with exit code 0

3.6.4 接合(joining)

joining 可以将stream中的元素用特定的连接符(没有的话,则直接连接)连接成一个字符串。

public class JoiningTest {public static void main(String[] args) {//Collectors.joining("分隔符"),用于拼接List<Person> list = new ArrayList<>();list.add(new Person("Tom", 8900, 23, "male", "New York"));list.add(new Person("Jack", 7000, 25, "male", "Washington"));list.add(new Person("Lily", 7800, 21, "female", "Washington"));//所有员工姓名,用逗号","隔开String names = list.stream().map(Person::getName).collect(Collectors.joining(","));System.out.println("所有员工的姓名:" + names);//用"-"拼接集合中的字符串List<String> list2 = Arrays.asList("A", "B", "C");String str = list2.stream().collect(Collectors.joining("-"));System.out.println("拼接后的字符串:" + str);}
}

输出结果:

所有员工的姓名:Tom,Jack,Lily
拼接后的字符串:A-B-CProcess finished with exit code 0

3.6.5 归约(reducing)

Collectors类提供的reducing方法,相比于stream本身的reduce方法,增加了对自定义归约的支持

public class StreamReducing {public static void main(String[] args) {//学习reducing()List<Person> list = new ArrayList<>();list.add(new Person("Tom", 8900, 23, "male", "New York"));list.add(new Person("Jack", 7000, 25, "male", "Washington"));list.add(new Person("Lily", 7800, 21, "female", "Washington"));// 每个员工减去起征点税后的薪资之和--reducing()方法Integer sum = list.stream().collect(Collectors.reducing(0, Person::getSalary, (i, j) -> (i + j - 5000)));System.out.println("员工扣税薪资总和:" + sum);//stream的reduce()方法Optional<Integer> sum2 = list.stream().map(Person::getSalary).reduce(Integer::sum);System.out.println("员工薪资总和:" + sum2.get());}
}

输出结果:

员工扣税薪资总和:8700
员工薪资总和:23700Process finished with exit code 0

3.7 排序(sorted)---自然排序调用的是equals()方法

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

  • sorted():自然排序,流中元素需实现Comparable接口
  • sorted(Comparator com):Comparator排序器---自定义排序

案例:将员工按工资由高到低(工资一样则按年龄由大到小)排序

public class SortedTest {public static void main(String[] args) {//将员工按工资由高到低(工资一样则按年龄由大到小)排序List<Person> list = new ArrayList<Person>();list.add(new Person("Sherry", 9000, 24, "female", "New York"));list.add(new Person("Tom", 8900, 22, "male", "Washington"));list.add(new Person("Jack", 9000, 25, "male", "Washington"));list.add(new Person("Lily", 8800, 26, "male", "New York"));list.add(new Person("Alisa", 9000, 26, "female", "New York"));//按工资升序排序(自然排序)List<String> newList = list.stream().sorted(Comparator.comparing(Person::getSalary)).map(Person::getName).collect(Collectors.toList());// 按工资倒序排序 reversed() 反转   map(Person::getName)-->映射到人名上List<String> newList2 = list.stream().sorted(Comparator.comparing(Person::getSalary).reversed()).map(Person::getName).collect(Collectors.toList());// 先按工资再按年龄升序排序 -->先按工资排序,工资相同,按年龄升序排List<String> newList3 = list.stream().sorted(Comparator.comparing(Person::getSalary).thenComparing(Person::getAge)).map(Person::getName).collect(Collectors.toList());// 先按工资再按年龄 自定义排序(降序), map(Person::getName)-->映射到人名上List<String> newList4 = list.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());System.out.println("按工资升序排序:" + newList);System.out.println("按工资降序排序:" + newList2);System.out.println("先按工资再按年龄升序排序:" + newList3);System.out.println("先按工资再按年龄自定义降序排序:" + newList4);}
}

输出结果:

按工资升序排序:[Lily, Tom, Sherry, Jack, Alisa]
按工资降序排序:[Sherry, Jack, Alisa, Tom, Lily]
先按工资再按年龄升序排序:[Lily, Tom, Sherry, Jack, Alisa]
先按工资再按年龄自定义降序排序:[Alisa, Jack, Sherry, Tom, Lily]Process finished with exit code 0

3.8 提取/组合--中间操作

流也可以进行合并、去重、限制、跳过等操作。

去重: distinct()

限制: limit()

跳过: skip()

concat() 合并流

limit() 限制取数

skip() 跳过元素

案例一:

public class ConcatTest {public static void main(String[] args) {//concat合并流操作ArrayList<String> list = new ArrayList<>();list.add("林青霞");list.add("王祖贤");list.add("张曼玉");list.add("张敏");list.add("钟丽缇");list.add("朱茵");list.add("莫文蔚");//取前4个数据组成一个流Stream<String> s1 = list.stream().limit(4);// 跳过2个数据组成一个流Stream<String> s2 = list.stream().skip(2);//合并上述得到的2个流,并输出结果Stream<String> concatStream = Stream.concat(s1, s2);//concatStream.forEach(System.out::println);/*** @Author Vincent* @Description //TODO** 注意:* 1. 上面2个流合并后,下面不能再合并,会报IllegalStateException异常* 2. 上面进行forEach()终止操作后,下面也不能进行forEach()终止操作也会报IllegalStateException异常**///把上述的合并流去重,要求字符串元素不能重复,并把结果输出concatStream.distinct().forEach(System.out::println);}
}

输出结果:

林青霞
王祖贤
张曼玉
张敏
钟丽缇
朱茵
莫文蔚Process finished with exit code 0

案例二:

public class ExtractCombTest {public static void main(String[] args) {//流也可以进行合并、去重、限制、跳过等操作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个数据 --从1开始,+2,无限迭代,取前10个元素List<Integer> collect = Stream.iterate(1, x -> x + 2).limit(10).collect(Collectors.toList());// skip:跳过前n个数据 --从1开始,+2,无限迭代,跳过第1个元素,取前5个元素List<Integer> collect2 = Stream.iterate(1, x -> x + 2).skip(1).limit(5).collect(Collectors.toList());System.out.println("流合并:" + newList);System.out.println("limit:" + collect);System.out.println("skip:" + collect2);}
}

输出结果:

流合并:[a, b, c, d, e, f, g]
limit:[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
skip:[3, 5, 7, 9, 11]Process finished with exit code 0

部分内容借鉴于此:(40条消息) Java8 Stream:2万字20个实例,玩转集合的筛选、归约、分组、聚合_云深不知处-CSDN博客_java stream 聚合

Java8 Stream 流的创建、筛选、映射、排序、归约、分组、聚合、提取与组合、收集、接合、foreach遍历相关推荐

  1. java8 stream流操作集合交集,差集,并集,过滤,分组,去重,排序,聚合等

    测试对象 public class Person {private String name;private Integer age;private Integer weight;public Pers ...

  2. Java8——Stream流

    Java8--Stream流 Stream是数据渠道,用于操作集合.数组等生成的元素序列. Stream操作的三个步骤: 创建Stream 中间操作 终止操作 一.获取stream的四种方式 1.通过 ...

  3. 学习Java8 Stream流,让我们更加便捷的操纵集合

    1. 概述 本篇文章会简略的介绍一下 Lambda 表达式,然后开启我们的正题 Java8 Stream 流,希望观众老爷们多多支持,并在评论区批评指正! Java8 的 Stream 流使用的是函数 ...

  4. 跟我学 Java 8 新特性之 Stream 流(五)映射

    转载自   跟我学 Java 8 新特性之 Stream 流(五)映射 经过了前面四篇文章的学习,相信大家对Stream流已经是相当的熟悉了,同时也掌握了一些高级功能了,如果你之前有阅读过集合框架的基 ...

  5. java8 Stream流【华为3面】

    华为三面@java8 stream流操作面试题 前言:华为三面考了个很简单的基础编程,就是java8 Stream流操作,太久没写,也是没掌握好java基础直接搞得措手不及,stream两行代码的事情 ...

  6. java8 stream流 将一个list转换成list

    java8 stream流 将一个对象集合转换成另一个对象集合 案例一: // 利用stream进行类型转化     List<String> stringList = new Array ...

  7. Java8 Stream 流 一些使用整理(持续更新)

    Java8 Stream 流 一些使用整理 双循环判断值 原始写法 Stream 普通写法 Stream filter + anyMatch写法 持续更新中 双循环判断值 原始写法 List<C ...

  8. Java8 Stream流式编程,极大解放你的生产力!

    java8自带常用的函数式接口 Predicate<T> boolean test(T t) 传入一个参数返回boolean值 Consumer<T> void accept( ...

  9. 玩转 Java8 Stream 流,常用方法,详细用法大合集!

    点击上方"Java精选",选择"设为星标" 别问别人为什么,多问自己凭什么! 下方有惊喜留言必回,有问必答! 每一天进步一点点,是成功的开始... 一.概述 S ...

最新文章

  1. 图像分区域合成,这个新方法实现了人脸的「精准整容」
  2. 单点登陆的技术实现机制
  3. 免费CDN加速隐藏你的服务器原ip以防别人攻击
  4. leetcode算法题--石子游戏 II★★
  5. 【bzoj1195】[HNOI2006]最短母串 AC自动机+状态压缩+BFS最短路
  6. 膨胀的JavaBeans –不要在您的API中添加“ Getters”
  7. 笨方法“学习python笔记之数学计算
  8. Linux: .bash_profile 与 .bashrc 的区别
  9. ImageNet标签竟然部分有误!数据集MNIST也会出错?
  10. 长期没有工作是什么感觉?
  11. [leedcode 229] Majority Element II
  12. Quartus II 13.1入门级使用方法 -仿真篇,适用于小白
  13. 普林斯顿微积分读本篇二:三角学
  14. 为何大厂APP如微信、支付宝、淘宝、手Q等只适配了armeabi-v7a/armeabi?
  15. 简要概述网络安全保障体系的总体框架
  16. 图片大小、像素、分辨率之间的关系
  17. background-image无法显示图片
  18. 【干货】Dialog的高冷用法
  19. BDB的Btree结构以及影响Btree性能的各种配置和方法
  20. 01 Java体系

热门文章

  1. oracle数据库--Oracle双引号和单引号的区别小结
  2. 股票换手率排行 API数据接口
  3. 理解离散傅立叶变换(四. 复数形式离散傅立叶变换)
  4. 经典滤波器的设计原理
  5. 《P道理-ERP项目实施手记》出版了,敬请关注!
  6. 高完整性系统工程(十一):Fault Tolerant Design
  7. B/S上传大文件的三种解决方案
  8. 信息安全应用为什么用c语言,阅读下列说明和c语言代码,回答问题1至问题4,将解答写在答题纸的对应栏内。【说明 - 信管网...
  9. 2022安全员-A证考试题模拟考试题库及在线模拟考试
  10. winform 发布应用程序 提示 “未能注册模块(程序路径)\ieframe.dll”