创建Stream API
// Collection系列的stream()、parallelStream()
List list = new ArrayList<>();
Stream stream1 = list.stream();
// Arrays.stream()
String[] strings = new String[10];
Stream stream2 = Arrays.stream(strings);
// Stream.of()
Stream stream3 = Stream.of("www", "baozi", "abc");
// 创建无限流
Stream stream4 = Stream.iterate(0, (x) -> x + 2);
中间操作
filter
// 中间操作:
Stream stream = emps.stream()
.filter((e) -> {
System.out.println("Stream API 的中间操作");
return e.getAge() > 21;
});
// 终端操作:
stream.forEach(System.out::println);
/*
Stream API 的中间操作
Employee{name='baozi3', age=23}
Stream API 的中间操作
Employee{name='baozi4', age=24}
Stream API 的中间操作
Stream API 的中间操作
Employee{name='baozi5', age=25}
Stream API 的中间操作
Employee{name='baozi2', age=22}
*/
limit
emps.stream()
.filter((e) -> {
System.out.println("短路");
return e.getAge() > 21;
})
.limit(2)
.forEach(System.out::println);
/*
短路
Employee{name='baozi3', age=23}
短路
Employee{name='baozi4', age=24}
*/
skip: 跳过前N个
emps.stream()
.skip(2) // 跳过前N个
.forEach(System.out::println);
distinct: 去重
emps.stream()
.distinct() // 根据hashcode和equals去重,所以需要重写hashcode和equals
.forEach(System.out::println);
map
List strs = Arrays.asList("aaa", "bbb", "ccc", "ddd", "eee");
strs.stream()
.map((str) -> str.toUpperCase())
.forEach(System.out::println);
/*
AAA
BBB
CCC
DDD
EEE
*/
emps.stream()
.map((e) -> e.getName())
.distinct()
.forEach(System.out::println);
/*
baozi3
baozi4
baozi1
baozi5
baozi2
*/
flatMap
@Test
public void flatMapTest() {
String[] strs = {"baozi"};
Stream> ss = Arrays.stream(strs)
.map(StreamTest::toChar);
ss.forEach(stream -> {
stream.forEach(System.out::println);
});
Stream stream = Arrays.stream(strs)
.flatMap(StreamTest::toChar);
stream.forEach(System.out::println);
}
public static Stream toChar(String str) {
List chars = new ArrayList<>();
for (char c : str.toCharArray()) {
chars.add(c);
}
return chars.stream();
}
sorted
List list = Arrays.asList("aaa", "bbb", "ccc");
list.stream()
.sorted() // 自然排(Comparable)
.forEach(System.out::println);
emps.stream()
// 定制排(Comparator)
.sorted((e1,e2) -> {
if (e1.getAge() == e2.getAge()) {
return e1.getName().compareTo(e2.getName());
} else {
return e1.getAge().compareTo(e2.getAge());
}
})
.forEach(System.out::println);
终端操作
allMatch: 所有元素都匹配
boolean b = emps.stream()
.allMatch((e) -> e.getStatus().equals(Employee.Status.BUSY));
System.out.println(b);
// false
anyMatch: 至少一个元素匹配
boolean b = emps.stream()
.anyMatch((e) -> e.getStatus().equals(Employee.Status.BUSY));
System.out.println(b);
// true
noneMatch: 所有元素都不匹配
boolean b = emps.stream()
.noneMatch((e) -> e.getStatus().equals(Employee.Status.BUSY));
System.out.println(b);
// false
findFirst: 返回第一个
Optional op = emps.stream()
.findFirst();
System.out.println(op.orElse(null));
findAny: 返回任意元素
Optional op = emps.stream()
.findAny();
System.out.println(op.orElse(null));
count
emps.stream().count()
max
Optional op1 = emps.stream()
.max(Comparator.comparingDouble(e -> e.getSalary()));
Optional op2 = emps.stream()
.map(e -> e.getSalary())
.max(Double::compare);
System.out.println(op1.get());
System.out.println(op2.get());
min
Optional op1 = emps.stream()
.min(Comparator.comparingDouble(e -> e.getSalary()));
Optional op2 = emps.stream()
.map(e -> e.getSalary())
.min(Double::compare);
System.out.println(op1.get());
System.out.println(op2.get());
reduce: 将流中的数据返回结合:x+y的结果下次作为x继续加下一个y
List list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
Integer sum = list.stream()
.reduce(0, (x, y) -> x + y);
System.out.println(sum);
// 55
Optional op = emps.stream()
.map(Employee::getSalary)
.reduce(Double::sum);
System.out.println(op.get());
// 30055.0
collect: 给stream中元素做汇总的方法
List list = emps.stream()
.map(Employee::getName)
.collect(Collectors.toList());
list.forEach(System.out::println);
// ---------------------------------------
Set set = emps.stream()
.map(Employee::getName)
.collect(Collectors.toSet());
set.forEach(System.out::println);
// ---------------------------------------
HashSet hashSet = emps.stream()
.map(Employee::getName)
.collect(Collectors.toCollection(HashSet::new));
hashSet.forEach(System.out::println);
// 总数 ---------------------------------------
Long count = emps.stream()
.collect(Collectors.counting());
// emps.stream().count();
// emps.size();
System.out.println(count);
// 平均值 ---------------------------------------
Double avg = emps.stream()
.collect(Collectors.averagingDouble(Employee::getSalary));
System.out.println(avg);
// 总和 ---------------------------------------
Double sum = emps.stream()
.collect(Collectors.summingDouble(Employee::getSalary));
System.out.println(sum);
// emps.stream()
// .mapToDouble(Employee::getSalary)
// .sum();
// 最大值 ---------------------------------------
Optional max = emps.stream()
.collect(Collectors.maxBy(Comparator.comparingDouble(e -> e.getSalary())));
// emps.stream()
// .max(Comparator.comparingDouble(e -> e.getSalary()));
Optional max2 = emps.stream()
.map(Employee::getSalary)
.collect(Collectors.maxBy(Double::compare));
// emps.stream()
// .map(Employee::getSalary)
// .max(Double::compare);
System.out.println(max.get());
System.out.println(max2.get());
// 最小值 minBy---------------------------------------
// join
String str = emps.stream()
.map(Employee::getName)
.collect(Collectors.joining(","));
System.out.println(str);
// 分组
Map> map = emps.stream()
.collect(Collectors.groupingBy(Employee::getStatus));
System.out.println(map);
// 多级分组
Map>> map2 = emps.stream()
.collect(Collectors.groupingBy(Employee::getStatus, Collectors.groupingBy((e) -> {
if (((Employee)e).getAge() <= 22) {
return "青年";
} else if (((Employee) e).getAge() <= 23) {
return "中年";
} else {
return "老年";
}
})));
System.out.println(map2);
Map> map = emps.stream()
.collect(Collectors.partitioningBy((e) -> e.getSalary() > 8000));
System.out.println(map);
DoubleSummaryStatistics dss = emps.stream()
.collect(Collectors.summarizingDouble(Employee::getSalary));
System.out.println(dss.getAverage());
System.out.println(dss.getCount());
System.out.println(dss.getMax());
System.out.println(dss.getMax());
System.out.println(dss.getSum());