Java流Stream实战-常用api案例解析

本文介绍java 8 Stream流的常用高频api,通过实战级别的案例进行演示。实现结合实际业务、开发需要来应用技术,不让技术讲解枯燥无味,带来技术落地成生产力的价值。


1. 思考,stream 的多个操作,相当于几个for循环,实际执行了几次循环?

List<String> collect = strings.stream()

// peek1

.peek(e -> out.println("Original Element: " + e))

// filter

.filter(e -> e.length() > 3)

// peek2

.peek(e -> out.println("Filtered value: " + e))

//map

.map(String::toUpperCase)

//peek3

.peek(e -> out.println("Mapped value: " + e))

// collect

.collect(Collectors.toList());

2. Lambda 的 peek 和 forEach 区别

  • peek 返回值是和之前流泛型相同的流, 多用于打印中间操作时元素数据

  • forEach 没有返回值, 无法继续使用点语法操作

/**

* @author zhangcq

* @version 1.0.0

* @title

* @date 2022/6/9 13:50

*/

public class PeekAndForEachExample {

public static void main(String[] args) {

PrintStream out = System.out;

final List<String> strings

= Arrays.asList("one", "two", "three", "four");

List<String> result = new ArrayList<>();

/**~~~~~~~重点看这里~~~~~~~~~~~~~~~~~~~~**/

for (String e : strings) {

// peek1

out.println("Original Element: " + e);

// filter

if (e.length() > 3) {

// peek2

out.println("Filtered value: " + e);

//map

e = e.toUpperCase();

//peek3

out.println("Mapped value: " + e);

// collect

result.add(e);

}

}

System.out.println("stream collect: " + result);

out.println("Final Results: " + strings);

out.println("~~~~~~~~~~~~~~~~~~~~~");

List<String> collect = strings.stream()

// peek1</

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值