高阶函数
定义:
是其它函数对象的使用者
作用:
将通用、复杂的逻辑隐含在高阶函数内部;
将易变、未定的逻辑放在外部的函数对象中。
内循环案例:
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
import java.util.function.Consumer;
/**
* @author millyxiong
* @version 1.0
* @ClassName InnerLoop
* @Description
* @date 2024/4/19 15:43
*/
public class InnerLoop {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
hiOrder(list, (val) -> System.out.println(val));
}
public static void hiOrder(List<Integer> list, Consumer<Integer> consumer) {
ListIterator<Integer> ite = list.listIterator(list.size());
while(ite.hasPrevious()){
Integer val = ite.previous();
consumer.accept(val);
}
}
}
二叉树简化案例:
简单流案例:
简单流化简案例:
简单流收集 Set 案例:
简单流收集 字符串 案例:
简单流收集 Map 案例:
Stream
filter
import java.util.stream.Stream;
/**
* @author millyxiong
* @version 1.0
* @ClassName FilterFunc
* @Description
* @date 2024/4/19 15:55
*/
public class FilterFunc {
public static void main(String[] args) {
Stream.of(
new Fruit("草莓", "Strawberry", "浆果", "红色"),
new Fruit("桑葚", "Mulberry", "浆果", "紫色"),
new Fruit("杨梅", "Waxberry", "浆果", "红色"),
new Fruit("核桃", "Walnut", "坚果", "棕色"),
new Fruit("花生", "Peanut", "坚果", "棕色"),
new Fruit("蓝莓", "Bulberry", "浆果", "蓝色")
).filter(f -> f.category.equals("浆果"))
.filter(c -> c.color.equals("蓝色"))
.forEach(System.out::println);
}
static class Fruit {
private String cname;
private String name;
private String category;
private String color;
public Fruit(String cname, String name, String category, String color) {
this.cname = cname;
this.name = name;
this.category = category;
this.color = color;
}
public String getCname() {
return cname;
}
public void setCname(String cname) {
this.cname = cname;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
@Override
public String toString() {
return "Fruit{" +
"cname='" + cname + '\'' +
", name='" + name + '\'' +
", category='" + category + '\'' +
", color='" + color + '\'' +
'}';
}
}
}
flatMap
扁平化(降维)
例如: 将二维的数据变成一维的数据
关键字
Function
案例一:
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
/**
* @author millyxiong
* @version 1.0
* @ClassName FlatMapFunc
* @Description
* @date 2024/4/21 15:13
*/
public class FlatMapFunc {
public static void main(String[] args) {
List<Fruit> list1 = new ArrayList<>();
List<Fruit> list2 = new ArrayList<>();
list1.add( new Fruit("草莓", "Strawberry", "浆果", "红色"));
list1.add( new Fruit("桑葚", "Mulberry", "浆果", "紫色"));
list1.add( new Fruit("杨梅", "Waxberry", "浆果", "红色"));
list1.add( new Fruit("蓝莓", "Bulberry", "浆果", "蓝色"));
list2.add( new Fruit("核桃", "Walnut", "坚果", "棕色"));
list2.add( new Fruit("花生", "Peanut", "坚果", "棕色"));
// Stream.of(
// list1, list2
// ).forEach(System.out::println);
Stream.of(list1, list2).flatMap(list -> list.stream()).forEach(System.out::println);
}
static class Fruit {
private String cname;
private String name;
private String category;
private String color;
public Fruit(String cname, String name, String category, String color) {
this.cname = cname;
this.name = name;
this.category = category;
this.color = color;
}
public String getCname() {
return cname;
}
public void setCname(String cname) {
this.cname = cname;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
@Override
public String toString() {
return "Fruit{" +
"cname='" + cname + '\'' +
", name='" + name + '\'' +
", category='" + category + '\'' +
", color='" + color + '\'' +
'}';
}
}
}
案例二:
public class FlatMapFunc_02 {
public static void main(String[] args) {
Integer[][] array2D = {
{1,2,3},
{4,5,6},
{7,8,9}
};
Arrays.stream(array2D).flatMap(list -> Arrays.stream(list)).forEach(System.out::println);
}
}
构建流
用已有数据构建出Stream 对象
从集合构建
集合.stream()
从数组构建
Arrays.stream(数组)
从对象构建
Stream.of(对象 ...)
案例:
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Stream;
/**
* @author millyxiong
* @version 1.0
* @ClassName BuildStreamFunc
* @Description
* @date 2024/4/21 15:25
*/
public class BuildStreamFunc {
public static void main(String[] args) {
//从集合构建
List.of(1,2,3).stream().forEach(System.out::println);
Set.of(1,2,3).stream().forEach(System.out::println);
Map.of("a",1,"b",2).entrySet().stream().forEach(System.out::println);
//从数组构建
int[] array = {1,2,3};
Arrays.stream(array).forEach(System.out::println);
//从对象构建
Stream.of(1,2,3,4,5).forEach(System.out::println);
}
}
合并和截取
合并:Stream.concat(流1, 流2);
public class ConcatStreamFunc {
public static void main(String[] args) {
Stream<Integer> stream1 = Stream.of(1, 2, 3);
Stream<Integer> stream2 = Stream.of(4, 5, 6);
Stream.concat(stream1, stream2).forEach(System.out::println);
}
}
截取:
根据位置
skip(long n) 跳过 n 个数据,保留剩下的
public class ConcatStreamFunc {
public static void main(String[] args) {
Stream<Integer> stream1 = Stream.of(1, 2, 3);
Stream<Integer> stream2 = Stream.of(4, 5, 6);
Stream<Integer> concat = Stream.concat(stream1, stream2);
concat.skip(2).forEach(System.out::println);
}
}
limit(long n) 保留 n 个数据,剩下的不要
public class ConcatStreamFunc {
public static void main(String[] args) {
Stream<Integer> stream1 = Stream.of(1, 2, 3);
Stream<Integer> stream2 = Stream.of(4, 5, 6);
Stream<Integer> concat = Stream.concat(stream1, stream2);
concat.limit(2).forEach(System.out::println);
}
}
根据条件
takeWhile(Predicate p) 条件成立保留,一旦条件不成立,剩下的不要
案例:一旦小于3的数据不成立,后面的数据就算成立也舍弃
public class ConcatStreamFunc {
public static void main(String[] args) {
Stream<Integer> stream1 = Stream.of(1, 2, 3);
Stream<Integer> stream2 = Stream.of(4, 5, 6);
Stream<Integer> concat = Stream.concat(stream1, stream2);
concat.takeWhile( x -> x < 3).forEach(System.out::println);
}
}
dropWhile(Predicate p) 条件成立舍弃,一旦条件不成立,剩下的保留
案例:一旦条件小于3不成立,后面的数据就算也不成立,也会保留
public class ConcatStreamFunc {
public static void main(String[] args) {
Stream<Integer> stream1 = Stream.of(1, 2, 3);
Stream<Integer> stream2 = Stream.of(4, 5, 6, 1);
Stream<Integer> concat = Stream.concat(stream1, stream2);
concat.dropWhile( x -> x < 3).forEach(System.out::println);
}
}
生成流
不用现有数据生成 Stream 对象
简单生成
IntStream.range(...)
依赖上一个值生成当前值
IntStream.iterate(...)
不依赖上一个值生成当前值
IntStream.generate(...)
案例:
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.IntStream;
/**
* @author millyxiong
* @version 1.0
* @ClassName GenerateStreamFunc
* @Description
* @date 2024/4/21 15:49
*/
public class GenerateStreamFunc {
public static void main(String[] args) {
// IntStream.range() 范围此处是:含头不含尾
IntStream.range(1,10).forEach(System.out::println);
System.out.println("--------------");
// IntStream.rangeClosed() 范围此处是:含头也含尾
IntStream.rangeClosed(1,9).forEach(System.out::println);
System.out.println("--------------");
// IntStream.iterate 生成 1 3 5 7 9 。。。 奇数序列,后一个元素根据上一个元素的值生成
IntStream.iterate(1, x -> x+2).limit(10).forEach(System.out::println);
System.out.println("--------------");
IntStream.iterate(1, x -> x<=9, x -> x+2).forEach(System.out::println);
System.out.println("--------------");
//生成 5 个随机数
IntStream.generate( () -> ThreadLocalRandom.current().nextInt(100)).limit(5).forEach(System.out::println);
System.out.println("--------------");
ThreadLocalRandom.current().ints(5, 0, 100).forEach(System.out::println);
System.out.println("--------------");
}
}
查找和判断
查找
filter(Predicate p).findAny();
filter(Predicate p).findFirst();
判断
anyMatch(Predicate p);
allMatch(Predicate p);
noneMatch(Predicate p);
find 案例
import java.util.stream.IntStream;
/**
* @author millyxiong
* @version 1.0
* @ClassName FindStreamFunc
* @Description
* @date 2024/4/21 16:01
*/
public class FindStreamFunc {
public static void main(String[] args) {
IntStream stream = IntStream.of(1, 4, 5, 6, 7);
// findFirst
// System.out.println(stream.filter(x -> (x & 1) == 0).findFirst().orElse(-1));
// System.out.println("----------------");
// stream.filter(x -> (x & 1) == 0).findFirst().ifPresent( x -> System.out.println(x));
// System.out.println("----------------");
// findAny
stream.filter( x -> (x & 1) == 0).findAny().ifPresent( x -> System.out.println(x));
}
}
match 案例
import java.util.stream.IntStream;
/**
* @author millyxiong
* @version 1.0
* @ClassName MatchStreamFunc
* @Description
* @date 2024/4/21 16:07
*/
public class MatchStreamFunc {
public static void main(String[] args) {
IntStream stream = IntStream.of(1, 3, 2, 54, 6);
// System.out.println(stream.anyMatch(x -> (x & 1) == 0));
// System.out.println("-----------------");
// System.out.println(stream.allMatch(x -> (x & 1) == 0));
// System.out.println("-----------------");
System.out.println(stream.noneMatch(x -> (x & 1) == 0));
System.out.println("-----------------");
}
}
去重–distinct
案例:
import java.util.stream.IntStream;
/**
* @author millyxiong
* @version 1.0
* @ClassName DistinctStreamFunc
* @Description
* @date 2024/4/21 16:10
*/
public class DistinctStreamFunc {
public static void main(String[] args) {
IntStream.of(1,2,3,4,2,1,5)
.distinct()
.forEach(System.out::println);
}
}
排序
案例:
import java.util.Comparator;
import java.util.stream.Stream;
/**
* @author millyxiong
* @version 1.0
* @ClassName SortStreamFunc
* @Description
* @date 2024/4/21 16:11
*/
public class SortStreamFunc {
public static void main(String[] args) {
// 按照 strength 进行升序排列
Stream.of(
new Hero("令狐冲", 99),
new Hero("肖建", 93),
new Hero("任我行", 99),
new Hero("张无忌", 87),
new Hero("赵敏", 70),
new Hero("周芷若", 60),
new Hero("朱茵", 10),
new Hero("东方不败", 42)
// ).sorted((a,b) -> Integer.compare(a.strength, b.strength))
).sorted(Comparator.comparingInt(Hero::strength))
.forEach(System.out::println);
System.out.println("---------------------------");
// 按照 strength 进行降序排列
Stream.of(
new Hero("令狐冲", 99),
new Hero("肖建", 93),
new Hero("任我行", 99),
new Hero("张无忌", 87),
new Hero("赵敏", 70),
new Hero("周芷若", 60),
new Hero("朱茵", 10),
new Hero("东方不败", 42)
).sorted(Comparator.comparingInt(Hero::strength).reversed())
.forEach(System.out::println);
System.out.println("---------------------------");
// 按照 strength 进行降序排列,相同 strength 按照名字长度升序
Stream.of(
new Hero("令狐冲", 99),
new Hero("肖建", 93),
new Hero("任我行", 99),
new Hero("张无忌", 93),
new Hero("赵敏", 70),
new Hero("周芷若", 60),
new Hero("朱茵", 10),
new Hero("东方不败", 42)
).sorted(Comparator.comparingInt(Hero::strength).reversed().thenComparingInt(n -> n.name().length()))
.forEach(System.out::println);
}
record Hero(String name, int strength) {
}
}
简化–reduce
化简: 两两合并,只剩一个
适合:求最大、最小、求和、求个数
方式:
.reduce((p,x) -> r) p 表示上次的结果, x 当前元素, r 本次合并的结果
.reduce(init, (p, x) ->r)
.reduce(init, (p, x) -> r, (r, r1) -> r2)
案例:
import java.util.Comparator;
import java.util.Optional;
import java.util.stream.Stream;
/**
* @author millyxiong
* @version 1.0
* @ClassName ReduceStreamFunc
* @Description
* @date 2024/4/21 16:29
*/
public class ReduceStreamFunc {
public static void main(String[] args) {
Stream<Hero> stream = Stream.of(
new Hero("令狐冲", 99),
new Hero("肖建", 93),
new Hero("任我行", 99),
new Hero("张无忌", 93),
new Hero("赵敏", 70),
new Hero("周芷若", 60),
new Hero("朱茵", 10),
new Hero("东方不败", 42)
);
// 合并, 获取最大 Strength 对象
// Optional<Hero> reduce = stream.reduce((a, b) -> a.strength() > b.strength() ? a : b);
// 合并, 给一个默认值,获取 Strength 大于 100 的对象 中 Strength 最大 的对象
// Hero reduce = stream.filter(c -> c.strength > 100).reduce(new Hero("-", -1), (a, b) -> a.strength() > b.strength() ? a : b);
// 获取总数
// Integer integer = stream.map(h -> 1).reduce(0, (a, b) -> a + b);
// System.out.println(integer);
// System.out.println(stream.count());
//求最大值
// System.out.println(stream.max(Comparator.comparingInt(Hero::strength)));
//求最小值
// System.out.println(stream.min(Comparator.comparingInt(Hero::strength)));
//求和
// System.out.println(stream.mapToInt(Hero::strength).sum());
// 求平均值
System.out.println(stream.mapToInt(Hero::strength).average());
System.out.println("--------------");
}
record Hero(String name, int strength) {
}
}
收集
将元素收集入容器
.collecgt( () -> c, (c, x) -> void, ?)
() -> c 创建容器c
(c, x) -> void 将元素 x 加入 容器 c
案例1:
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
/**
* @author millyxiong
* @version 1.0
* @ClassName CollectStreamFunc
* @Description
* @date 2024/4/21 17:00
*/
public class CollectStreamFunc {
public static void main(String[] args) {
Stream<String> stream = Stream.of("令狐冲", "周芷若", "灭绝师太", "金毛狮王", "独孤求败", "任我行", "东方不败", "赵敏", "朱儿");
List<String> res = stream.collect(() -> new ArrayList<>(), (list, x) -> list.add(x), (a, b) -> {
});
for (String re : res) {
System.out.println(re);
}
}
}
优化案例1:
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
/**
* @author millyxiong
* @version 1.0
* @ClassName CollectStreamFunc
* @Description
* @date 2024/4/21 17:00
*/
public class CollectStreamFunc {
public static void main(String[] args) {
Stream<String> stream = Stream.of("令狐冲", "周芷若", "灭绝师太", "金毛狮王", "独孤求败", "任我行", "东方不败", "赵敏", "朱儿");
// ArrayList::new () -> new ArrayList()
// ArrayList::add (list, x) -> list.add(x)
List<String> res = stream.collect(ArrayList::new, ArrayList::add, (a, b) -> {
});
for (String re : res) {
System.out.println(re);
}
}
}
案例2:
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Stream;
/**
* @author millyxiong
* @version 1.0
* @ClassName CollectStreamFunc
* @Description
* @date 2024/4/21 17:00
*/
public class CollectStreamFunc {
public static void main(String[] args) {
Stream<String> stream = Stream.of("令狐冲", "周芷若", "东方不败", "赵敏", "朱儿", "灭绝师太", "金毛狮王", "独孤求败", "任我行", "东方不败", "赵敏", "朱儿");
Set<String> res = stream.collect(HashSet::new, HashSet::add, (a, b) -> {
});
for (String re : res) {
System.out.println(re);
}
}
}
案例3:
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Stream;
/**
* @author millyxiong
* @version 1.0
* @ClassName CollectStreamFunc
* @Description
* @date 2024/4/21 17:00
*/
public class CollectStreamFunc {
public static void main(String[] args) {
Stream<String> stream = Stream.of("令狐冲", "周芷若", "东方不败", "赵敏", "朱儿", "灭绝师太", "金毛狮王", "独孤求败", "任我行", "东方不败", "赵敏", "朱儿");
Map<String, Integer> res = stream.collect(HashMap::new, (map, x) -> map.put(x, 1), (a, b) -> {
});
System.out.println(res);
}
}
案例4:
import java.util.stream.Stream;
/**
* @author millyxiong
* @version 1.0
* @ClassName CollectStreamFunc
* @Description
* @date 2024/4/21 17:00
*/
public class CollectStreamFunc {
public static void main(String[] args) {
Stream<String> stream = Stream.of("令狐冲", "周芷若", "东方不败", "赵敏", "朱儿", "灭绝师太", "金毛狮王", "独孤求败", "任我行", "东方不败", "赵敏", "朱儿");
StringBuilder sb = stream.collect(StringBuilder::new, StringBuilder::append, (a, b) -> {
});
System.out.println(sb);
}
}
案例5:
import java.util.StringJoiner;
import java.util.stream.Stream;
/**
* @author millyxiong
* @version 1.0
* @ClassName CollectStreamFunc
* @Description
* @date 2024/4/21 17:00
*/
public class CollectStreamFunc {
public static void main(String[] args) {
Stream<String> stream = Stream.of("令狐冲", "周芷若", "东方不败", "赵敏", "朱儿", "灭绝师太", "金毛狮王", "独孤求败", "任我行", "东方不败", "赵敏", "朱儿");
StringJoiner stringJoiner = stream.collect(() -> new StringJoiner(","), StringJoiner::add, (a, b) -> {
});
System.out.println(stringJoiner);
}
}
收集器
案例:
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* @author millyxiong
* @version 1.0
* @ClassName CollectStreamFunc
* @Description
* @date 2024/4/21 17:00
*/
public class CollectStreamFunc {
public static void main(String[] args) {
Stream<String> stream = Stream.of("令狐冲", "周芷若", "东方不败", "赵敏", "朱儿", "灭绝师太", "金毛狮王", "独孤求败", "任我行");
//收集到 List
// List<String> list = stream.collect(Collectors.toList());
// for (String s : list) {
// System.out.println(s);
// }
//收集到 Set
// Set<String> set = stream.collect(Collectors.toSet());
// for (String s : set) {
// System.out.println(s);
// }
//收集到 Map
// Map<String, Integer> map = stream.collect(Collectors.toMap(x -> x, x -> 1));
// System.out.println(map);
//收集到 StringBuilder
// String collect = stream.collect(Collectors.joining());
// System.out.println(collect);
//收集到 StringJoiner
// String collect1 = stream.collect(Collectors.joining(","));
// System.out.println(collect1);
// 分组收集器
// Collectors.groupingBy 上游收集器
// Collectors.toList() 下游收集器
Map<Integer, List<String>> collect = stream.collect(Collectors.groupingBy(x -> x.length(), Collectors.toList()));
System.out.println(collect);
}
}
Stream-下游收集器
配合 .groupingBy 使用的下游收集器有如下:
Mapping(x -> y, dc )
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* @author millyxiong
* @version 1.0
* @ClassName DownCollectStreamFunc
* @Description
* @date 2024/4/21 17:33
*/
public class DownCollectStreamFunc {
public static void main(String[] args) {
Stream<Hero> stream = Stream.of(
new Hero("令狐冲", 99),
new Hero("肖建", 93),
new Hero("任我行", 99),
new Hero("张无忌", 93),
new Hero("赵敏", 70),
new Hero("周芷若", 60),
new Hero("朱茵", 10),
new Hero("东方不败", 42)
);
// mapping(x -> y, dc)
// 需求:根据名字的长度进行分组,分组后只保存 strength
Map<Integer, List<Integer>> collect = stream.collect(
Collectors.groupingBy(x -> x.name().length(), Collectors.mapping(y -> y.strength(), Collectors.toList())));
System.out.println(collect);
}
record Hero(String name, int strength) {
}
}
filtering(x -> boolean, dc)
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* @author millyxiong
* @version 1.0
* @ClassName DownCollectStreamFunc
* @Description
* @date 2024/4/21 17:33
*/
public class DownCollectStreamFunc {
public static void main(String[] args) {
Stream<Hero> stream = Stream.of(
new Hero("令狐冲", 99),
new Hero("肖建", 93),
new Hero("任我行", 99),
new Hero("张无忌", 93),
new Hero("赵敏", 70),
new Hero("周芷若", 60),
new Hero("朱茵", 10),
new Hero("东方不败", 42)
);
// filtering(x -> boolean, dc)
// 需求:根据名字长度分组,然后过滤掉 Strength 小于 90 的
Map<Integer, List<Hero>> collect = stream.collect(
Collectors.groupingBy(x -> x.name().length(), Collectors.filtering(y -> y.strength() >= 90, Collectors.toList())));
System.out.println(collect);
}
record Hero(String name, int strength) {
}
}
flatMapping( x -> substream, dc)
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* @author millyxiong
* @version 1.0
* @ClassName DownCollectStreamFunc
* @Description
* @date 2024/4/21 17:33
*/
public class DownCollectStreamFunc {
public static void main(String[] args) {
Stream<Hero> stream = Stream.of(
new Hero("令狐冲", 99),
new Hero("肖建", 93),
new Hero("任我行", 99),
new Hero("张无忌", 93),
new Hero("赵敏", 70),
new Hero("周芷若", 60),
new Hero("朱茵", 10),
new Hero("东方不败", 42)
);
// flatMapping( x -> subStream, dc)
// 需求:根据名字长度分组,然后将分组后的人名切成单个字符
Map<Integer, List<String>> collect = stream.collect(
Collectors.groupingBy(x -> x.name().length(), Collectors.flatMapping(
y -> y.name().chars().mapToObj(Character::toString),
Collectors.toList()
)));
System.out.println(collect);
}
record Hero(String name, int strength) {
}
}
counting
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* @author millyxiong
* @version 1.0
* @ClassName DownCollectStreamFunc
* @Description
* @date 2024/4/21 17:33
*/
public class DownCollectStreamFunc {
public static void main(String[] args) {
Stream<Hero> stream = Stream.of(
new Hero("令狐冲", 99),
new Hero("肖建", 93),
new Hero("任我行", 99),
new Hero("张无忌", 93),
new Hero("赵敏", 70),
new Hero("周芷若", 60),
new Hero("朱茵", 10),
new Hero("东方不败", 42)
);
// counting()
// 需求:根据名字长度分组,然后求每组个数
Map<Integer, Long> collect = stream.collect(
Collectors.groupingBy(x -> x.name().length(), Collectors.counting()));
System.out.println(collect);
}
record Hero(String name, int strength) {
}
}
minBy( (a,b) -> int )
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* @author millyxiong
* @version 1.0
* @ClassName DownCollectStreamFunc
* @Description
* @date 2024/4/21 17:33
*/
public class DownCollectStreamFunc {
public static void main(String[] args) {
Stream<Hero> stream = Stream.of(
new Hero("令狐冲", 99),
new Hero("肖建", 93),
new Hero("任我行", 99),
new Hero("张无忌", 93),
new Hero("赵敏", 70),
new Hero("周芷若", 60),
new Hero("朱茵", 10),
new Hero("东方不败", 42)
);
// minBy( (a,b) -> int)
// 需求:根据名字长度分组,然后求每组 strength 最低的
Map<Integer, Optional<Hero>> collect = stream.collect(
Collectors.groupingBy(x -> x.name().length(), Collectors.minBy(
Comparator.comparingInt(Hero::strength)
)));
System.out.println(collect);
}
record Hero(String name, int strength) {
}
}
reducing( init, (p,x) -> r)
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* @author millyxiong
* @version 1.0
* @ClassName DownCollectStreamFunc
* @Description
* @date 2024/4/21 17:33
*/
public class DownCollectStreamFunc {
public static void main(String[] args) {
Stream<Hero> stream = Stream.of(
new Hero("令狐冲", 99),
new Hero("肖建", 93),
new Hero("任我行", 99),
new Hero("张无忌", 93),
new Hero("赵敏", 70),
new Hero("周芷若", 60),
new Hero("朱茵", 10),
new Hero("东方不败", 42)
);
// reducing(init, (p,x) -> r)
// 需求:根据名字长度分组,然后求每组 strength 进行求和
Map<Integer, Integer> collect = stream.collect(
Collectors.groupingBy(x -> x.name().length(),
Collectors.mapping(h -> h.strength(),
Collectors.reducing(0, (p,y) -> p + y))));
System.out.println(collect);
}
record Hero(String name, int strength) {
}
}
基本类型流
int 流
import java.util.IntSummaryStatistics;
import java.util.stream.IntStream;
/**
* @author millyxiong
* @version 1.0
* @ClassName IntStreamFunc
* @Description
* @date 2024/4/22 20:18
*/
public class IntStreamFunc {
public static void main(String[] args) {
IntStream a = IntStream.of(97, 98, 99);
// a.mapToObj(Character::toString).forEach(System.out::println);
IntSummaryStatistics summaryStatistics = a.summaryStatistics();
System.out.println(summaryStatistics.getMax());
System.out.println(summaryStatistics.getMin());
System.out.println(summaryStatistics.getCount());
System.out.println(summaryStatistics.getAverage());
System.out.println(summaryStatistics.getSum());
}
}
stream 转换
import java.util.stream.Stream;
/**
* @author millyxiong
* @version 1.0
* @ClassName IntStreamFunc
* @Description
* @date 2024/4/22 20:18
*/
public class IntStreamFunc {
public static void main(String[] args) {
Stream<Hero> heroStream = Stream.of(
new Hero("令狐冲", 90),
new Hero("风清扬", 88)
);
heroStream.mapToInt(Hero::strength).forEach(System.out::println);
}
record Hero(String name, Integer strength) {
}
}
Stream 流的特性
一次使用; 两类操作
一次使用案例:
import java.util.stream.Stream;
/**
* @author millyxiong
* @version 1.0
* @ClassName StreamFunc_03
* @Description
* @date 2024/4/22 20:26
*/
public class StreamFunc_03 {
public static void main(String[] args) {
Stream<Integer> stream = Stream.of(1, 3, 4, 5, 6, 7);
stream.forEach(System.out::println);
stream.forEach(System.out::println);
}
}
两类操作案例:
中间操作,终结操作(中间操作 lazy 懒惰, 终结操作 eager 迫切)
import java.util.stream.Stream;
/**
* @author millyxiong
* @version 1.0
* @ClassName StreamFunc_03
* @Description
* @date 2024/4/22 20:26
*/
public class StreamFunc_03 {
public static void main(String[] args) {
Stream<Integer> stream = Stream.of(1, 3, 4, 5, 6, 7);
stream.map(x -> x + 1).filter(x -> x < 5) .forEach(System.out::println);
}
}
Stream 总结