groupingBy
和 flatMap
是 Java 8 引入的 Stream API 中的两个重要操作。
counting
, summingInt
, averagingDouble
等)结合使用,进行复杂的数据分析。假设我们有一个 Person
类,包含姓名和年龄两个属性:
public class Person {
private String name;
private int age;
// 构造函数、getter 和 setter 省略
}
我们可以使用 groupingBy
对一组人按年龄进行分组:
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class GroupingByExample {
public static void main(String[] args) {
List<Person> people = List.of(
new Person("Alice", 25),
new Person("Bob", 30),
new Person("Charlie", 25)
);
Map<Integer, List<Person>> peopleByAge = people.stream()
.collect(Collectors.groupingBy(Person::getAge));
System.out.println(peopleByAge);
}
}
假设我们有一个包含多个列表的列表,我们希望将其扁平化为一个单一的列表:
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class FlatMapExample {
public static void main(String[] args) {
List<List<Integer>> nestedLists = List.of(
List.of(1, 2, 3),
List.of(4, 5),
List.of(6, 7, 8, 9)
);
List<Integer> flattenedList = nestedLists.stream()
.flatMap(List::stream)
.collect(Collectors.toList());
System.out.println(flattenedList);
}
}
原因:groupingBy
默认使用 HashMap
作为底层实现,HashMap
不保证键的顺序。
解决方法:可以使用 LinkedHashMap
来保持键的插入顺序:
Map<Integer, List<Person>> peopleByAge = people.stream()
.collect(Collectors.groupingBy(Person::getAge, LinkedHashMap::new, Collectors.toList()));
原因:如果嵌套流中的某个元素为 null
,调用 flatMap
时会抛出空指针异常。
解决方法:在使用 flatMap
之前,先过滤掉 null
值:
List<List<Integer>> nestedLists = List.of(
List.of(1, 2, 3),
null,
List.of(6, 7, 8, 9)
);
List<Integer> flattenedList = nestedLists.stream()
.filter(list -> list != null) // 过滤掉 null 值
.flatMap(List::stream)
.collect(Collectors.toList());
希望这些信息对你有所帮助!
没有搜到相关的沙龙
领取专属 10元无门槛券
手把手带您无忧上云