记录一下,方便以后查询,就是怕自己记不住
方法 | 作用 |
---|---|
filter() | 接收lambda,从流中排除某些操作 |
limit() | 截断流,使其元素不超过给定对象 |
skip(n) | 跳过元素,返回一个扔掉了前n个元素的流,若流中元素不足n个,则返回一个空流,与limit(n)互补 |
distinct | 筛选,通过流所生成元素的hashCode()和equals去除重复元素 |
map | 接受Lambda,将元素转换成其他形式或提取信息。接受一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素 |
sorted() | 自然排序(Comparable) |
sorted(Comparator com) | 定制排序(Comparator) |
allMatch | 检查是否匹配所有元素 |
anyMatch | 检查是否至少匹配一个元素 |
noneMatch | 检查是否没有匹配所有元素 |
findFirst | 返回第一个元素 |
findAny | 返回当前流中的任意元素 |
count | 返回流中元素的总个数 |
max | 返回流中最大值 |
min | 返回流中最小值 |
reduce | 归约操作可以将流中元素反复结合起来,得到一个值 |
collect | 将流转换为其他形式,接收一个Collector接口实现,用于给Stream中汇总的方法 |
reversed | 返序排序 |
mapToInt/mapToDouble/mapToIong | 将 Stream 中的元素映射为 double/long/int 类型,并返回一个 DoubleStream/LongStream/IntStream。 |
orElse | 表示如果Optional.ofNullable中的对象为空,则返回一个新的对象。 |
ifPresent | 表示如果存在值,则使用该值调用指定的使用者,否则不执行任何操作。 |
forEach | 遍历集合。 |
下面是一堆的代码o(╥﹏╥)o
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.stereotype.Component;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
@Data
@AllArgsConstructor
@NoArgsConstructor
class Person {
private String name; // 姓名
private int salary; // 薪资
private int age; // 年龄
private String sex; //性别
private String area; // 地区
}
@Component
public class StreamUtils {
public static void main(String[] args) {
//通过 java.util.Collection.stream() 方法用集合创建流
List<String> list = Arrays.asList("a", "b", "c");
// 创建一个顺序流
Stream<String> streamStream = list.stream();
// 创建一个并行流
Stream<String> parallelStream = list.parallelStream();
//使用java.util.Arrays.stream(T[] array)方法用数组创建流
int[] array = {1, 3, 5, 6, 8};
IntStream streamList = Arrays.stream(array);
//使用Stream的静态方法:of()、iterate()、generate()
Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5, 6);
Stream<Integer> stream2 = Stream.iterate(0, (x) -> x + 3).limit(4);
List<Integer> collect3 = Stream.iterate(0, (x) -> x + 3).limit(4).collect(Collectors.toList());
stream2.forEach(System.out::println);
/**
* 打印结果如下
* 0
* 3
* 6
* 9
*/
System.out.println("=================");
Stream<Double> stream3 = Stream.generate(Math::random).limit(3);
stream3.forEach(System.out::println);
/**
* 打印结果如下
* 0.27226280230300126
* 0.4999115108316934
* 0.6706437099209988
*/
System.out.println("=================");
List<Integer> list1 = Arrays.asList(7, 6, 9, 3, 8, 2, 1);
// 遍历输出符合条件的元素(大于6的元素)
list1.stream().filter(x -> x > 6).forEach(System.out::println);
/**
* 打印结果如下:
* 7
* 9
* 8
*/
System.out.println("=================");
// 匹配第一个元素
Optional<Integer> findFirst = list1.stream().filter(x -> x > 6).findFirst();
// 匹配任意(适用于并行流)
Optional<Integer> findAny = list1.parallelStream().filter(x -> x > 6).findAny();
// 是否包含符合特定条件的元素
boolean anyMatch = list1.stream().anyMatch(x -> x > 6);
System.out.println("匹配第一个值:" + findFirst.get());
System.out.println("匹配任意一个值:" + findAny.get());
System.out.println("是否存在大于6的值:" + anyMatch);
/**
* 打印结果如下:
* 匹配第一个值:7
* 匹配任意一个值:8
* 是否存在大于6的值:true
*/
System.out.println("=================");
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"));
personList.add(new Person("Owen", 9500, 25, "male", "New York"));
personList.add(new Person("Alisa", 7900, 26, "female", "New York"));
List<String> collect = personList.stream().filter(e -> e.getSalary() > 8000).map(Person::getName).collect(Collectors.toList());
System.out.println("collect = " + collect);
/**
* 打印结果如下:
* collect = [Tom, Anni, Owen]
*/
System.out.println("=================");
String collect1 = personList.stream().filter(e -> e.getSalary() > 8000).map(Person::getName).collect(Collectors.joining("#"));
System.out.println("collect1 = " + collect1);
/**
* 打印结果如下:
* collect1 = Tom#Anni#Owen
*/
System.out.println("=================");
//获取Person集合中年龄最大的元素。
Person person = personList.stream().max(Comparator.comparing(Person::getAge)).get();
System.out.println("年龄最大的元素是 = " + person.toString());
/**
* 打印结果如下:
* 年龄最大的元素是 = Person(name=Alisa, salary=7900, age=26, sex=female, area=New York)
*/
System.out.println("=================");
//获取String集合中最长的元素。
List<String> listTest = Arrays.asList("adnm", "admmt", "pot", "xbangd", "weoujgsd");
String s = listTest.stream().max(Comparator.comparing(String::length)).get();
System.out.println("最长的元素是 = " + s);
/**
* 打印结果如下:
* 最长的元素是 = weoujgsd
*/
System.out.println("=================");
//获取Integer集合中的最大值。
List<Integer> listTestInteger = Arrays.asList(7, 6, 9, 4, 11, 6);
Integer integer = listTestInteger.stream().max(Integer::compareTo).get();
System.out.println("Integer集合中的最大值是(自然排序) = " + integer);
/**
* 打印结果如下:
* Integer集合中的最大值是(自然排序) = 11
*/
System.out.println("=================");
//Integer integer1 = listTestInteger.stream().max(Comparator.comparingInt(o -> o)).get();
Integer integer1 = listTestInteger.stream().max((o1, o2) -> o1 - o2).get();
System.out.println("Integer集合中的最大值是(自定义排序(从大到小排序)) = " + integer1);
/**
* 打印结果如下:
* Integer集合中的最大值是(自定义排序(从大到小排序)) = 4
*/
System.out.println("=================");
//获取员工薪资最高的人。
Person person1 = personList.stream().max(Comparator.comparingInt(Person::getSalary)).get();
System.out.println("员工薪资最高的人是 = " + person1.toString());
/**
* 打印结果如下:
* 员工薪资最高的人是 = Person(name=Owen, salary=9500, age=25, sex=male, area=New York)
*/
System.out.println("=================");
String[] strArr = {"abcd", "bcdd", "defde", "fTr"};
//将每个元素转换为大写并且返回list集合
List<String> strList = Arrays.stream(strArr).map(String::toUpperCase).collect(Collectors.toList());
System.out.println("每个元素大写:" + strList);
/**
* 打印结果如下:
* 每个元素大写:[ABCD, BCDD, DEFDE, FTR]
*/
System.out.println("=================");
//每个元素+3
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("每个元素+3:" + intListNew);
/**
* 打印结果如下:
* 每个元素+3:[4, 6, 8, 10, 12, 14]
*/
System.out.println("=================");
//将两个字符数组合并成一个新的字符数组。
List<String> listArrays = Arrays.asList("m,k,l,a", "1,3,5,7");
List<String> listNew = listArrays.stream().flatMap(x -> {
// 将每个元素转换成一个stream
String[] split = x.split(",");
Stream<String> s2 = Arrays.stream(split);
return s2;
}).collect(Collectors.toList());
System.out.println("集合长度: " + listArrays.size() + ",处理前的集合:" + listArrays);
System.out.println("集合长度: " + listNew.size() + ",处理后的集合:" + listNew);
/**
* 打印结果如下:
* 集合长度: 2,处理前的集合:[m,k,l,a, 1,3,5,7]
* 集合长度: 8,处理后的集合:[m, k, l, a, 1, 3, 5, 7]
*/
System.out.println("=================");
// 最小值
double minPerson = personList.stream().mapToDouble(Person::getSalary).min().orElse(0);
System.out.println("minPerson = " + minPerson);
/**
* 打印结果如下:
* minPerson = 7000.0
*/
System.out.println("=================");
// 最大值
double maxPerson = personList.stream().mapToDouble(Person::getSalary).max().orElse(0);
System.out.println("maxPerson = " + maxPerson);
/**
* 打印结果如下:
* maxPerson = 9500.0
*/
System.out.println("=================");
// 求和
double sumPerson = personList.stream().mapToDouble(Person::getSalary).sum();
System.out.println("sumPerson = " + sumPerson);
/**
* 打印结果如下:
* sumPerson = 49300.0
*/
System.out.println("=================");
// 总数
double countPerson = personList.stream().mapToDouble(Person::getSalary).min().orElse(0);
System.out.println("countPerson = " + countPerson);
/**
* 打印结果如下:
* countPerson = 7000.0
*/
System.out.println("=================");
// 平均值
double averagePerson = personList.stream().mapToInt(Person::getSalary).average().orElse(0);
System.out.println("averagePerson = " + averagePerson);
/**
* 打印结果如下:
* averagePerson = 8216.666666666666
*/
System.out.println("=================");
// 返回:0
double min1Person = personList.stream().mapToDouble(Person::getSalary).min().orElse(0);
System.out.println("min1Person = " + min1Person);
/**
* 打印结果如下:
* min1Person = 7000.0
*/
System.out.println("=================");
// 无搜索元素异常: No value present
double min2Person = personList.stream().mapToDouble(Person::getSalary).min().getAsDouble();
System.out.println("min2Person = " + min2Person);
/**
* 打印结果如下:
* min2Person = 7000.0
*/
System.out.println("=================");
List<Integer> list11 = Arrays.asList(1, 6, 3, 4, 6, 7, 9, 6, 20);
List<Integer> listNew11 = list11.stream().filter(x -> x % 2 == 0).collect(Collectors.toList());
Set<Integer> set11 = list11.stream().filter(x -> x % 2 == 0).collect(Collectors.toSet());
List<Person> personList11 = new ArrayList<>();
personList11.add(new Person("Tom", 8900, 23, "male", "New York"));
personList11.add(new Person("Jack", 7000, 25, "male", "Washington"));
personList11.add(new Person("Lily", 7800, 21, "female", "Washington"));
personList11.add(new Person("Anni", 8200, 24, "female", "New York"));
Map<?, Person> map11 = personList11.stream().filter(p -> p.getSalary() > 8000)
.collect(Collectors.toMap(Person::getName, p -> p));
System.out.println("toList:" + listNew11);
System.out.println("toSet:" + set11);
System.out.println("toMap:" + map11);
/**
* 打印结果:
* toList:[6, 4, 6, 6, 20]
* toSet:[4, 20, 6]
* toMap:{Tom=Person(name=Tom, salary=8900, age=23, sex=male, area=New York), Anni=Person(name=Anni, salary=8200, age=24, sex=female, area=New York)}
*/
System.out.println("=================");
/**
* 计数:count
* 平均值:averagingInt、averagingLong、averagingDouble
* 最值:maxBy、minBy
* 求和:summingInt、summingLong、summingDouble
* 统计以上所有:summarizingInt、summarizingLong、summarizingDouble
*
*/
// 求总数
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 collect2 = personList.stream().collect(Collectors.summarizingDouble(Person::getSalary));
System.out.println("员工总数:" + count);
System.out.println("员工平均工资:" + average);
System.out.println("员工工资总和:" + sum);
System.out.println("员工工资所有统计:" + collect2);
/**
* 打印结果:
* 员工总数:6
* 员工平均工资:8216.666666666666
* 员工工资总和:49300
* 员工工资所有统计:DoubleSummaryStatistics{count=6, sum=49300.000000, min=7000.000000, average=8216.666667, max=9500.000000}
*/
System.out.println("=================");
//将员工按薪资是否高于8000分为两部分;将员工按性别和地区分组
Map<Boolean, List<Person>> part = personList.stream().collect(Collectors.partitioningBy(x -> x.getSalary() > 8000));
// 将员工按性别分组
Map<String, List<Person>> group = personList.stream().collect(Collectors.groupingBy(Person::getSex));
// 将员工先按性别分组,再按地区分组
Map<String, Map<String, List<Person>>> group2 = personList.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=[Person(name=Jack, salary=7000, age=25, sex=male, area=Washington), Person(name=Lily, salary=7800, age=21, sex=female, area=Washington), Person(name=Alisa, salary=7900, age=26, sex=female, area=New York)], true=[Person(name=Tom, salary=8900, age=23, sex=male, area=New York), Person(name=Anni, salary=8200, age=24, sex=female, area=New York), Person(name=Owen, salary=9500, age=25, sex=male, area=New York)]}
* 员工按性别分组情况:{female=[Person(name=Lily, salary=7800, age=21, sex=female, area=Washington), Person(name=Anni, salary=8200, age=24, sex=female, area=New York), Person(name=Alisa, salary=7900, age=26, sex=female, area=New York)], male=[Person(name=Tom, salary=8900, age=23, sex=male, area=New York), Person(name=Jack, salary=7000, age=25, sex=male, area=Washington), Person(name=Owen, salary=9500, age=25, sex=male, area=New York)]}
* 员工按性别、地区:{female={New York=[Person(name=Anni, salary=8200, age=24, sex=female, area=New York), Person(name=Alisa, salary=7900, age=26, sex=female, area=New York)], Washington=[Person(name=Lily, salary=7800, age=21, sex=female, area=Washington)]}, male={New York=[Person(name=Tom, salary=8900, age=23, sex=male, area=New York), Person(name=Owen, salary=9500, age=25, sex=male, area=New York)], Washington=[Person(name=Jack, salary=7000, age=25, sex=male, area=Washington)]}}
*/
System.out.println("=================");
//员工薪资总和
Integer integer2 = personList.stream().map(Person::getSalary).reduce(Integer::sum).get();
System.out.println("员工薪资总和为 = " + integer2);
//排序
// 按工资升序排序(自然排序)
List<String> newList = personList.stream().sorted(Comparator.comparing(Person::getSalary)).map(Person::getName)
.collect(Collectors.toList());
// 按工资倒序排序
List<String> newList2 = personList.stream().sorted(Comparator.comparing(Person::getSalary).reversed())
.map(Person::getName).collect(Collectors.toList());
// 先按工资再按年龄升序排序
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());
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]
*/
System.out.println("=================");
}
}