我有这些模型类:
public class Student extends Person;
public class Professor extends Person;
public class University {
private long id;
private String name;
private List<Person> employers;
....
}
我有一个大学列表,我想将其转换为 map ; Person是一个抽象类,并且实现了hashCode和equals方法。 这是一个带有 for 迭代的实现:
Map<Person, University> mapList = new HashMap<Person, University>();
for (University u : universities) {
for (Person p : u.getEmployers()) {
mapList.put(p,u);
}
}
mapList.forEach((k,v) -> System.out.println(k.toString() + v.getName()));
我对 Java 8 流不太熟悉,但是如何使用 lambda 表达式隐藏此代码?
最佳答案
其他答案可能与您的 Java 7 版本完全相同,在这种情况下,使用内置流内容,使用 forEach 方法可能会更简洁,但我想展示如何使用具有纯粹的 FP 风格操作,以便您可以扩展流媒体的舒适度。
您可以使用 lambda,但对于大多数函数来说不需要这样做,因为您可以使用方法引用:
universities.stream()
// create maps for each university
.map(u -> u.getEmployer().stream()
.collect(Collectors.toMap(Function.identity(), p -> u))
// You need the entry set to turn back into a stream
.map(Map::entrySet)
// flatten the entry sets into a single stream
.flatMap(Set::stream)
// finally collect into the final map
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue))
如果您有一个包含元组的库,那么这可以简化,因为您可以跳过中间映射。您还可以使用 Map.Entry 的内置实现,但我发现它们太冗长了,不值得。
如果静态导入 toMap、toList 等内容,流会更干净、更具可读性。
关于java - 使用流 Java 8 转换 Map<K,V> 中的 List<V>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44997500/