发布于 更新于
AI总结: 本文介绍了使用Java Stream API进行各种数据操作的示例,包括过滤、映射、排序、分组和转换等功能。具体操作包括:通过过滤器筛选长度大于5的字符串,映射字符串为大写,提取对象字段,类型转换,按字符串长度和字段排序,按年龄分组,以及将数组转换为列表。
优化建议:
1. 使用方法引用简化代码,例如在映射字符串为大写时,可以直接使用 String::toUpperCase。
2. 对于排序操作,可以使用Comparator.comparing方法提高可读性。
3. 在转换为Map时,考虑使用更明确的合并策略,以便于维护和理解。
4. 在数组转列表时,确保数组不为空以避免潜在的NullPointerException。
List<String> result = list.stream()
.filter(str -> str.length() > 5)
.collect(Collectors.toList());
List<String> result = list.stream()
.map(str -> str.toUpperCase())
.collect(Collectors.toList());
List<Integer> result = list.stream()
.map(c -> c.getId())
.collect(Collectors.toList());
List<Long> longList = stringList.stream()
.map(Long::parseLong)
.collect(Collectors.toList());
List<String> result = list.stream()
.sorted((str1, str2) -> str1.length() - str2.length())
.collect(Collectors.toList());
List<Person> result = list.stream()
.sorted(Comparator.comparing(Person::getAge).reversed())
.collect(Collectors.toList());
// 按年龄分组
Map<Integer, List<Student>> ageMap = studentList.stream()
.collect(Collectors.groupingBy(Student::getAge));
// key重复时, 取前值
Map<Long, User> map = list.stream()
.collect(Collectors.toMap(User::getId, Function.identity(), (v1, v2) -> v1))
// key重复时, 取后值
Map<Long, User> map = list.stream()
.collect(Collectors.toMap(User::getId, Function.identity(), (v1, v2) -> v2))
List<T> list = Arrays.stream(arrays).boxed().collect(Collectors.toList());