所以我有这门课:
class User {
public String name;
public Integer age;
public User(String name, Integer age) {
this.name = name;
this.age = age;
}
}
然后是这个 map
:
Map<String, Set<Integer>> map = new HashMap<>();
map.put("User", Set.of(18, 19, 20, 21));
我想在此处获取 4 个用户的列表:
- 姓名:“约翰”,年龄:18
- 姓名:“约翰”,年龄:19
- ....
- ....
有什么想法可以在 Java 8 中使用 streams
来实现吗?
最佳答案
List<User> users = map.entrySet()
.stream()
.flatMap(e -> e.getValue().stream().map(x -> new User(e.getKey(), x)))
.collect(Collectors.toList());
Set.of
是 java-9 btw
关于java - Map<String, Set<T>> 到 Java 8 中的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45758575/