九天猎人 发表于 5 天前

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

Lambda 函数和 peek 操作是 Java 8 Stream API 中非常有用的特性,下面我将介绍它们的利用案例。
Lambda 函数利用案例
Lambda 表达式是 Java 8 引入的一种简洁的匿名函数表现方式。
聚集操作
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");

// 使用 Lambda 表达式排序
Collections.sort(names, (a, b) -> a.compareTo(b));

// 使用 Lambda 表达式遍历
names.forEach(name -> System.out.println(name));

// 使用方法引用
names.forEach(System.out::println);
过滤和映射
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);

// 过滤偶数
List<Integer> evenNumbers = numbers.stream()
                                  .filter(n -> n % 2 == 0)
                                  .collect(Collectors.toList());

// 平方映射
List<Integer> squares = numbers.stream()
                               .map(n -> n * n)
                               .collect(Collectors.toList());
peek 操作利用案例
peek() 是 Stream API 中的一个中心操作,主要用于调试或观察流中的元素而不改变它们。
List<String> result = Stream.of("one", "two", "three", "four")
    .filter(e -> e.length() > 3)
    .peek(e -> System.out.println("Filtered value: " + e))
    .map(String::toUpperCase)
    .peek(e -> System.out.println("Mapped value: " + e))
    .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());
修改对象状态
List<User> users = getUsers();

List<User> updatedUsers = users.stream()
    .peek(user -> {
      if (user.getAge() > 30) {
            user.setGroup("Senior");
      }
    })
    .collect(Collectors.toList());
结合利用 Lambda 和 peek 的实用案例
案例1:日志调试
List<String> transactions = getTransactions();

List<String> validTransactions = transactions.stream()
    .filter(t -> t.startsWith("TX"))// Lambda 过滤
    .peek(t -> System.out.println("有效交易ID: " + t))// 调试日志
    .map(t -> t.toUpperCase())// Lambda 转换
    .collect(Collectors.toList());
案例2:性能监控
List<Data> bigData = getData();

long start = System.currentTimeMillis();

List<Data> processed = bigData.stream()
    .peek(d -> {
      if (System.currentTimeMillis() - start > 1000) {
            System.out.println("处理超时警告");
      }
    })
    .map(d -> processData(d))// 假设processData是一个处理方法
    .collect(Collectors.toList());
案例3:多步调处理
List<Product> products = getProducts();

List<Product> discountedProducts = products.stream()
    .peek(p -> System.out.println("原始价格: " + p.getPrice()))
    .filter(p -> p.getPrice() > 100)// 只处理高价商品
    .peek(p -> p.setPrice(p.getPrice() * 0.9))// 打9折
    .peek(p -> System.out.println("折扣后价格: " + p.getPrice()))
    .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() 是一个中心操作,用于观察流中的元素而不改变它们,主要用于调试。
List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David");
List<String> result = names.stream()
    .peek(name -> System.out.println("原始名字: " + name))
    .map(String::toUpperCase)
    .peek(name -> System.out.println("转换后: " + name))
    .collect(Collectors.toList());

[*]filter() - 过滤
filter() 根据条件过滤流中的元素。
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

// 过滤偶数
List<Integer> evenNumbers = numbers.stream()
    .filter(n -> n % 2 == 0)
    .collect(Collectors.toList());

// 过滤长度大于3的字符串
List<String> longNames = names.stream()
    .filter(name -> name.length() > 3)
    .collect(Collectors.toList());

[*]map() - 映射
map() 将流中的每个元素转换为另一个情势。
// 将字符串转换为大写
List<String> upperCaseNames = names.stream()
    .map(String::toUpperCase)
    .collect(Collectors.toList());

// 提取对象属性
List<Integer> nameLengths = names.stream()
    .map(String::length)
    .collect(Collectors.toList());

// 复杂映射
List<Employee> employees = getEmployees();
List<String> employeeNames = employees.stream()
    .map(Employee::getName)
    .collect(Collectors.toList());

[*]limit() - 截断
limit() 限制流中元素的数目。
// 只取前3个元素
List<Integer> firstThree = numbers.stream()
    .limit(3)
    .collect(Collectors.toList());

// 结合其他操作
List<String> result = names.stream()
    .filter(name -> name.length() > 3)
    .limit(2)
    .collect(Collectors.toList());

[*]skip() - 跳过
skip() 跳过流中的前N个元素。
// 跳过前2个元素
List<Integer> skipped = numbers.stream()
    .skip(2)
    .collect(Collectors.toList());

// 分页实现
int pageSize = 5;
int pageNumber = 2; // 第2页
List<String> page = names.stream()
    .skip((pageNumber - 1) * pageSize)
    .limit(pageSize)
    .collect(Collectors.toList());

[*]collect() - 收集
collect() 是一个终止操作,将流转换为聚集或其他情势。
// 转换为List
List<String> list = names.stream().collect(Collectors.toList());

// 转换为Set
Set<String> set = names.stream().collect(Collectors.toSet());

// 转换为Map
Map<String, Integer> nameLengthMap = names.stream()
    .collect(Collectors.toMap(
      name -> name,         // 键
      String::length         // 值
    ));

// 连接字符串
String joined = names.stream().collect(Collectors.joining(", "));

// 分组
Map<Integer, List<String>> groupByLength = names.stream()
    .collect(Collectors.groupingBy(String::length));

[*]distinct() - 去重
distinct() 去除流中的重复元素。
List<Integer> numbersWithDuplicates = Arrays.asList(1, 2, 2, 3, 4, 4, 5);

// 基本去重
List<Integer> distinctNumbers = numbersWithDuplicates.stream()
    .distinct()
    .collect(Collectors.toList());

// 对象去重(需要正确实现equals和hashCode)
List<Employee> distinctEmployees = employees.stream()
    .distinct()
    .collect(Collectors.toList());

// 结合其他操作
List<String> distinctLongNames = names.stream()
    .filter(name -> name.length() > 3)
    .distinct()
    .collect(Collectors.toList());
综合利用示例
List<Transaction> transactions = getTransactions();
// 复杂流处理
Map<String, Double> result = transactions.stream()
    .peek(t -> System.out.println("处理交易: " + t.getId()))// 调试
    .filter(t -> t.getAmount() > 1000)                     // 过滤小额交易
    .distinct()                                          // 去重
    .skip(5)                                             // 跳过前5条
    .limit(10)                                             // 只取10条
    .collect(Collectors.groupingBy(
      Transaction::getCurrency,                        // 按货币分组
      Collectors.summingDouble(Transaction::getAmount)   // 计算每种货币的总金额
    ));

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页: [1]
查看完整版本: Lambda 函数与 peek 操作的利用案例