1.Lambda+stream流

1.lambda
1.1定义:lambda核心是只有一个抽象函数的函数式接口
函数式接口:只有一个抽象函数,@FunctionalInterface修饰检查。
1.2作用:
1.2.1利用链式编程简化方法代码
1.2.2链式可以实现连续高阶编程
1.3主要接口
在这里插入图片描述

2.stream流中lambda表达式
2.1常用stream编程方法
.stream()
.filter(n->(n.))
.distinct()
.sorted(Comparator.comparing() )
.foreach( )
.skip(2)
.limit(1)
.reduce(())
.map()
.tomap()
.collect(Collectors.groupingBy())
.collect(Collectors.toArray() .toList() .toMap( , ,())
max().get()

2.2 流创建方法
2.2.1 Collection.stream()
集合转顺序流:List list = Arrays.asList(“a”, “b”, “c”); Stream stream = list.stream();

2.2.2 Collection.parallelStream()
创建并行流:Stream parallelStream = Arrays.asList(1,2,3).parallelStream();

2.2.3 Arrays.stream()
数组转流:IntStream intStream = Arrays.stream(new int[]{1,2,3});

2.2.4 Stream.of()
直接创建流:Stream stream = Stream.of(“A”, “B”, “C”);

2.2.5 Stream.iterate()
生成无限序列:Stream.iterate(0, n -> n+1).limit(5).forEach(System.out::print); // 输出01234

2.2.6 Stream.generate()
通过Supplier生成:Stream.generate(Math::random).limit(3).forEach(System.out::println);

2.2.7 原始类型特化流
整型范围流:IntStream.range(1,5).forEach(System.out::print); // 1234
文件行流:Files.lines(Paths.get(“data.txt”)).forEach(System.out::println);

2.3 中间操作
2.3.1 filter()
过滤偶数:Arrays.asList(1,2,3,4).stream().filter(n -> n%2==0).forEach(System.out::println); // 2,4

2.3.2 map()
字符串转长度:Stream.of(“apple”,“banana”).map(String::length).forEach(System.out::println); // 5,6

2.3.3 flatMap()
展平嵌套集合:List<List> nested = Arrays.asList(Arrays.asList(“a”),Arrays.asList(“b”));
nested.stream().flatMap(List::stream).forEach(System.out::println); // a b

2.3.4 distinct()
去重:Stream.of(1,2,2,3).distinct().forEach(System.out::println); // 1,2,3

2.3.5 sorted()
按长度排序:Stream.of(“apple”,“kiwi”).sorted(Comparator.comparing(String::length)).forEach(System.out::println); // kiwi,apple

2.3.6 peek()
调试查看:Stream.of(“a”,“b”).peek(System.out::print).map(String::toUpperCase).forEach(System.out::println); // aA bB

2.3.7 limit()
取前2个:IntStream.range(1,10).limit(2).forEach(System.out::println); // 1,2

2.3.8 skip()
跳过前2个:Stream.of(“A”,“B”,“C”,“D”).skip(2).forEach(System.out::println); // C,D

2.4 终止操作
2.4.1 forEach()
遍历输出:Stream.of(“red”,“blue”).forEach(c -> System.out.println("Color: "+c));

2.4.2 collect()
转List:List list = Stream.of(“a”,“b”).collect(Collectors.toList());
分组:Map<Integer,List> map = Stream.of(“a”,“bb”).collect(Collectors.groupingBy(String::length));

2.4.3 toArray()
转数组:String[] arr = Stream.of(“a”,“b”).toArray(String[]::new);

2.4.4 reduce()
求和:Optional sum = Stream.of(1,2,3).reduce(Integer::sum); // 6
字符串连接:String result = Stream.of(“a”,“b”,“c”).reduce(“”, String::concat); // “abc”

2.4.5 count()
计数:long count = Stream.of(“A”,“B”,“C”).count(); // 3

2.4.6 max()/min()
最长字符串:Optional max = Stream.of(“cat”,“elephant”).max(Comparator.comparingInt(String::length)); // elephant

2.4.7 findFirst()/findAny()
第一个元素:Optional first = Stream.of(“a”,“b”).findFirst(); // a
任意元素:Optional any = Stream.of(1,2,3).parallel().findAny();

2.4.8 条件匹配
存在大于3:boolean exists = Stream.of(1,2,3,4).anyMatch(n -> n>3); // true
全部偶数:boolean allEven = Stream.of(2,4,6).allMatch(n -> n%2==0); // true

2.5 收集器(Collectors)
2.5.1 toList()/toSet()
转List:List list = Stream.of(“a”,“b”).collect(Collectors.toList());
转Set:Set set = Stream.of(1,2,2).collect(Collectors.toSet()); // [1,2]

2.5.2 toMap()
创建映射:Map<String,Integer> map = Stream.of(“apple”).collect(Collectors.toMap(s->s, String::length)); // {apple=5}

2.5.3 groupingBy()
按长度分组:Map<Integer,List> groups = Stream.of(“a”,“bb”).collect(Collectors.groupingBy(String::length)); // {1=[“a”],2=[“bb”]}

2.5.4 partitioningBy()
奇偶分区:Map<Boolean,List> partition = Stream.of(1,2,3).collect(Collectors.partitioningBy(n->n%2==0)); // {false=[1,3], true=[2]}

2.5.5 joining()
字符串连接:String joined = Stream.of(“a”,“b”,“c”).collect(Collectors.joining(“,”)); // “a,b,c”

2.6 并行流
2.6.1 parallel()
转为并行流:List result = Arrays.asList(1,2,3).stream().parallel().filter(n->n>1).collect(Collectors.toList());

2.6.2 sequential()
转回顺序流:Arrays.asList(1,2,3).parallelStream().sequential().forEach(System.out::println);

3.补充知识点
3.1Collectors.groupingBy(A,Collectors.groupingBy(B))
3.1.1现象:实际产生<A , <B , [子集]>
3.1.2解释:第二个参数可以接受一个下游收集器(如另一个 Collectors.groupingBy),用于处理每个分组后的值
3.1.3 eg:
persons.stream().collect(Collectors.groupingBy(
Person::getCity,
Collectors.groupingBy(Person::getAge)
));
实际结果:Map<String(City), Map<Integer(Age), List > >

3.2compare函数族
3.2.1 Comparator.comparing()
Comparator.comparing(Function<T,U> keyExtractor)
作用:创建基于对象属性的比较器
eg: persons.sort(Comparator.comparing(Person::getName));

3.2.2 thenComparing()
Comparator.thenComparing(Function<T,U> keyExtractor)
作用:多级排序(主排序条件相同时)
eg: persons.sort(Comparator.comparing(Person::getCity)
.thenComparing(Person::getAge));

3.2.3 comparingInt/Long/Double
Comparator.comparingInt(ToIntFunction keyExtractor)
作用:原始类型特化比较器(避免装箱开销)
eg: persons.sort(Comparator.comparingInt(Person::getAge));

3.2.4 nullsFirst/nullsLast
Comparator.nullsFirst(Comparator comparator)
作用:处理null值的比较器
eg: Comparator nullSafe = Comparator.nullsFirst(
Comparator.comparing(Person::getName));
persons.sort(nullSafe);

3.2.5 naturalOrder/reverseOrder
Comparator.naturalOrder()
作用:自然顺序比较器
eg: List sorted = names.stream()
.sorted(Comparator.naturalOrder())
.collect(Collectors.toList());

3.3 流操作性能陷阱
3.3.1 有状态操作
危险操作:sorted(), distinct(), limit()在并行流中可能降低性能
解决方案:对小数据集使用顺序流,避免在并行流中多次调用有状态操作。

3.3.2 自动装箱开销
问题:原始类型流与对象流转换产生装箱开销
优化方案:
错误:IntStream.range(1,100).boxed().mapToInt(i->i).sum();
正确:IntStream.range(1,100).sum();

3.3.3 短路操作优化
高效操作:findFirst(), anyMatch(), limit()可提前终止流处理
应用场景:找到第一个满足条件的元素后立即终止:
eg: Optional person = persons.stream()
.filter(p -> p.getAge() > 30)
.findFirst();

3.4 并行流使用准则
3.4.1 适用场景
大型数据集(>10000元素)
高计算密度操作
无状态操作链

3.4.2 不适用场景
小数据集(并行开销>计算收益)
有状态操作(如sorted/distinct)
I/O密集型操作

3.4.3 线程安全保证
错误:非线程安全操作
List unsafeList = new ArrayList<>();
stream.parallel().forEach(unsafeList::add);

正确:使用线程安全收集器
List safeList = stream.parallel()
.collect(Collectors.toList());

3.5 其他重要注意点
3.5.1 方法引用优化
优先使用方法引用替代Lambda表达式:
String::length 替代 s -> s.length()

ArrayList::new 替代 () -> new ArrayList<>()

3.5.2 避免副作用
不要在Lambda表达式中修改外部状态:
错误示例:
int count = 0;
list.stream().forEach(s -> count++); // 副作用操作

正确示例:
long count = list.stream().count();

3.5.3 异常处理
Lambda表达式中的异常需要显式处理:
list.stream().map(s -> {
try {
return Integer.parseInt(s);
} catch (NumberFormatException e) {
return 0;}});

3.5.4 资源管理
使用try-with-resources管理流资源:
try (Stream lines = Files.lines(Paths.get(“file.txt”))) {
lines.forEach(System.out::println);}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值