Lambda 函数与 peek 操作的利用案例

打印 上一主题 下一主题

主题 1543|帖子 1543|积分 4629

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x
Lambda 函数和 peek 操作是 Java 8 Stream API 中非常有用的特性,下面我将介绍它们的利用案例。
Lambda 函数利用案例
Lambda 表达式是 Java 8 引入的一种简洁的匿名函数表现方式。
聚集操作
  1. List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
  2. // 使用 Lambda 表达式排序
  3. Collections.sort(names, (a, b) -> a.compareTo(b));
  4. // 使用 Lambda 表达式遍历
  5. names.forEach(name -> System.out.println(name));
  6. // 使用方法引用
  7. names.forEach(System.out::println);
复制代码
过滤和映射
  1. List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
  2. // 过滤偶数
  3. List<Integer> evenNumbers = numbers.stream()
  4.                                   .filter(n -> n % 2 == 0)
  5.                                   .collect(Collectors.toList());
  6. // 平方映射
  7. List<Integer> squares = numbers.stream()
  8.                                .map(n -> n * n)
  9.                                .collect(Collectors.toList());
复制代码
peek 操作利用案例
peek() 是 Stream API 中的一个中心操作,主要用于调试或观察流中的元素而不改变它们。
  1. List<String> result = Stream.of("one", "two", "three", "four")
  2.     .filter(e -> e.length() > 3)
  3.     .peek(e -> System.out.println("Filtered value: " + e))
  4.     .map(String::toUpperCase)
  5.     .peek(e -> System.out.println("Mapped value: " + e))
  6.     .collect(Collectors.toList());
复制代码
调试流操作
List numbers = Arrays.asList(1, 2, 3, 4, 5);
List result = numbers.stream()
.peek(x -> System.out.println("原始: " + x))
.map(x -> x * 2)
.peek(x -> System.out.println("乘2后: " + x))
.filter(x -> x > 5)
.peek(x -> System.out.println("过滤后: " + x))
.collect(Collectors.toList());
修改对象状态
  1. List<User> users = getUsers();
  2. List<User> updatedUsers = users.stream()
  3.     .peek(user -> {
  4.         if (user.getAge() > 30) {
  5.             user.setGroup("Senior");
  6.         }
  7.     })
  8.     .collect(Collectors.toList());
复制代码
结合利用 Lambda 和 peek 的实用案例
案例1:日志调试
  1. List<String> transactions = getTransactions();
  2. List<String> validTransactions = transactions.stream()
  3.     .filter(t -> t.startsWith("TX"))  // Lambda 过滤
  4.     .peek(t -> System.out.println("有效交易ID: " + t))  // 调试日志
  5.     .map(t -> t.toUpperCase())  // Lambda 转换
  6.     .collect(Collectors.toList());
复制代码
案例2:性能监控
  1. List<Data> bigData = getData();
  2. long start = System.currentTimeMillis();
  3. List<Data> processed = bigData.stream()
  4.     .peek(d -> {
  5.         if (System.currentTimeMillis() - start > 1000) {
  6.             System.out.println("处理超时警告");
  7.         }
  8.     })
  9.     .map(d -> processData(d))  // 假设processData是一个处理方法
  10.     .collect(Collectors.toList());
复制代码
案例3:多步调处理
  1. List<Product> products = getProducts();
  2. List<Product> discountedProducts = products.stream()
  3.     .peek(p -> System.out.println("原始价格: " + p.getPrice()))
  4.     .filter(p -> p.getPrice() > 100)  // 只处理高价商品
  5.     .peek(p -> p.setPrice(p.getPrice() * 0.9))  // 打9折
  6.     .peek(p -> System.out.println("折扣后价格: " + p.getPrice()))
  7.     .collect(Collectors.toList());
复制代码
注意事项
peek() 是一个中心操作,假如没有终止操作,它不会执行
不要滥用 peek() 来修改状态,这大概导致不可预期的活动
生产情况中应谨慎利用 peek() 进行日志记录,大概影响性能
Lambda 表达式应保持简洁,复杂逻辑应考虑利用方法引用或单独的方法
Lambda 和 peek 的组合为 Java 流式编程提供了强大的调试和观察本事,同时保持了代码的简洁性。
Java Stream API 常用操作详解
下面我将具体介绍 Java Stream API 中的 peek, filter, map, limit, skip, collect 和 distinct 等常用操作,并提供利用示例。

  • peek() - 流元素操作(调试用)
    peek() 是一个中心操作,用于观察流中的元素而不改变它们,主要用于调试。
  1. List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David");
  2. List<String> result = names.stream()
  3.     .peek(name -> System.out.println("原始名字: " + name))
  4.     .map(String::toUpperCase)
  5.     .peek(name -> System.out.println("转换后: " + name))
  6.     .collect(Collectors.toList());
复制代码

  • filter() - 过滤
    filter() 根据条件过滤流中的元素。
  1. List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
  2. // 过滤偶数
  3. List<Integer> evenNumbers = numbers.stream()
  4.     .filter(n -> n % 2 == 0)
  5.     .collect(Collectors.toList());
  6. // 过滤长度大于3的字符串
  7. List<String> longNames = names.stream()
  8.     .filter(name -> name.length() > 3)
  9.     .collect(Collectors.toList());
复制代码

  • map() - 映射
    map() 将流中的每个元素转换为另一个情势。
  1. // 将字符串转换为大写
  2. List<String> upperCaseNames = names.stream()
  3.     .map(String::toUpperCase)
  4.     .collect(Collectors.toList());
  5. // 提取对象属性
  6. List<Integer> nameLengths = names.stream()
  7.     .map(String::length)
  8.     .collect(Collectors.toList());
  9. // 复杂映射
  10. List<Employee> employees = getEmployees();
  11. List<String> employeeNames = employees.stream()
  12.     .map(Employee::getName)
  13.     .collect(Collectors.toList());
复制代码

  • limit() - 截断
    limit() 限制流中元素的数目。
  1. // 只取前3个元素
  2. List<Integer> firstThree = numbers.stream()
  3.     .limit(3)
  4.     .collect(Collectors.toList());
  5. // 结合其他操作
  6. List<String> result = names.stream()
  7.     .filter(name -> name.length() > 3)
  8.     .limit(2)
  9.     .collect(Collectors.toList());
复制代码

  • skip() - 跳过
    skip() 跳过流中的前N个元素。
  1. // 跳过前2个元素
  2. List<Integer> skipped = numbers.stream()
  3.     .skip(2)
  4.     .collect(Collectors.toList());
  5. // 分页实现
  6. int pageSize = 5;
  7. int pageNumber = 2; // 第2页
  8. List<String> page = names.stream()
  9.     .skip((pageNumber - 1) * pageSize)
  10.     .limit(pageSize)
  11.     .collect(Collectors.toList());
复制代码

  • collect() - 收集
    collect() 是一个终止操作,将流转换为聚集或其他情势。
  1. // 转换为List
  2. List<String> list = names.stream().collect(Collectors.toList());
  3. // 转换为Set
  4. Set<String> set = names.stream().collect(Collectors.toSet());
  5. // 转换为Map
  6. Map<String, Integer> nameLengthMap = names.stream()
  7.     .collect(Collectors.toMap(
  8.         name -> name,         // 键
  9.         String::length         // 值
  10.     ));
  11. // 连接字符串
  12. String joined = names.stream().collect(Collectors.joining(", "));
  13. // 分组
  14. Map<Integer, List<String>> groupByLength = names.stream()
  15.     .collect(Collectors.groupingBy(String::length));
复制代码

  • distinct() - 去重
    distinct() 去除流中的重复元素。
  1. List<Integer> numbersWithDuplicates = Arrays.asList(1, 2, 2, 3, 4, 4, 5);
  2. // 基本去重
  3. List<Integer> distinctNumbers = numbersWithDuplicates.stream()
  4.     .distinct()
  5.     .collect(Collectors.toList());
  6. // 对象去重(需要正确实现equals和hashCode)
  7. List<Employee> distinctEmployees = employees.stream()
  8.     .distinct()
  9.     .collect(Collectors.toList());
  10. // 结合其他操作
  11. List<String> distinctLongNames = names.stream()
  12.     .filter(name -> name.length() > 3)
  13.     .distinct()
  14.     .collect(Collectors.toList());
复制代码
综合利用示例
  1. List<Transaction> transactions = getTransactions();
  2. // 复杂流处理
  3. Map<String, Double> result = transactions.stream()
  4.     .peek(t -> System.out.println("处理交易: " + t.getId()))  // 调试
  5.     .filter(t -> t.getAmount() > 1000)                     // 过滤小额交易
  6.     .distinct()                                            // 去重
  7.     .skip(5)                                               // 跳过前5条
  8.     .limit(10)                                             // 只取10条
  9.     .collect(Collectors.groupingBy(
  10.         Transaction::getCurrency,                          // 按货币分组
  11.         Collectors.summingDouble(Transaction::getAmount)   // 计算每种货币的总金额
  12.     ));
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

九天猎人

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表