一句话总结,类似于ES6中的多维数组展平 ?1. flatMap实践
实体类
class User {
Integer id;
String name;
List<String> hobby;
}
调用
public static void main(String[] args) {
List<String> hobby1 = Arrays.asList("java", "c", "音乐");
List<String> hobby2 = Arrays.asList("c++", "c", "游戏");
List<User> users = Arrays.asList(new User(1, "张三", hobby1), new User(2, "李四", hobby2));
List<String> result = users.stream()
.map(user -> user.hobby)
.flatMap(Collection::stream)
.distinct()
.collect(Collectors.toList());
System.out.println(result);
}
?2. flatMap实践
public static void main(String[] args) {
List<List<String>> testList = Arrays.asList(Arrays.asList("aa", "bb", "cc"), Arrays.asList("bb", "cc", "dd"));
List<String> list = testList.stream().flatMap(Collection::stream).collect(Collectors.toList());
System.out.println(list);
}
参考资料 1. Java基础之Java8中map和flatMap的使用
|