stream.collect 是 Java Stream API 中的一个非常有用的方法,它可以将流中的元素收集到不同类型的集合中,如列表、集合或映射。在实际项目中,stream.collect 可以用于处理和转换数据,以满足特定需求。以下是一些使用 stream.collect 的实际项目案例:
Map<Department, List<Employee>> employeesByDepartment = employees.stream() .collect(Collectors.groupingBy(Employee::getDepartment));计算每个员工的年龄,并将其存储在一个新的列表中:List<Integer> ages = employees.stream() .map(Employee::getAge) .collect(Collectors.toList());将字符串列表转换为大写形式,并用逗号连接:String upperCaseWords = words.stream() .map(String::toUpperCase) .collect(Collectors.joining(","));从员工列表中获取年龄最大的员工:Optional<Employee> oldestEmployee = employees.stream() .collect(Collectors.maxBy(Comparator.comparing(Employee::getAge)));将员工列表按照年龄进行排序,并将其存储在一个新的列表中:List<Employee> sortedEmployees = employees.stream() .sorted(Comparator.comparing(Employee::getAge)) .collect(Collectors.toList());将员工列表中的所有姓名转换为小写,并存储在一个集合中:Set<String> lowerCaseNames = employees.stream() .map(Employee::getName) .map(String::toLowerCase) .collect(Collectors.toSet());这些案例展示了 stream.collect 在实际项目中的多种应用场景。通过使用 stream.collect,我们可以轻松地对数据进行转换、分组和排序等操作。


