数据过滤和筛选:
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> evenNumbers = numbers.stream()
.filter(n -> n % 2 == 0)
.collect(Collectors.toList()); // 筛选出偶数
数据转换和映射:
List<String> names = Arrays.asList("John", "Alice", "Bob");
List<String> upperCaseNames = names.stream()
.map(String::toUpperCase)
.collect(Collectors.toList()); // 将名称转换为大写
数据排序和排序后处理:
List<Integer> numbers = Arrays.asList(5, 2, 8, 3, 1);
List<Integer> sortedNumbers = numbers.stream()
.sorted()
.collect(Collectors.toList()); // 对数字进行升序排序
Optional<Integer> maxNumber = numbers.stream()
.max(Comparator.naturalOrder()); // 获取最大值
数据分组和分区:
List<Person> people = Arrays.asList(
new Person("John", 25),
new Person("Alice", 30),
new Person("Bob", 25),
new Person("Emily", 30)
);
Map<Integer, List<Person>> peopleByAge = people.stream()
.collect(Collectors.groupingBy(Person::getAge)); // 按年龄分组
Map<Boolean, List<Person>> peopleByAgePartition = people.stream()
.collect(Collectors.partitioningBy(person -> person.getAge() >= 30)); // 根据年龄是否大于等于30进行分区
数据统计和聚合:
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
long count = numbers.stream().count(); // 计算元素数量
Optional<Integer> sum = numbers.stream().reduce(Integer::sum); // 计算总和
OptionalDouble average = numbers.stream().mapToInt(Integer::intValue).average(); // 计算平均值
Optional<Integer> max = numbers.stream().max(Integer::compare); // 获取最大值
Optional<Integer> min = numbers.stream().min(Integer::compare); // 获取最小值
示例:
// 查询评论数据(不包括回复)
List<Comment> originList = articleComments.stream().filter(comment -> comment.getOriginId() == null).collect(Collectors.toList());