我有这样的情况
class A {
private B b;
public B getB() {
return b;
}
}
还有另一个B类
class B {
private List<C> c;
public List<C> getListC() {
return c;
}
}
现在类 C 包含两个实例变量
class C {
private int id;
private String name;
public int getId() {
return id;
}
public String getName() {
return name;
}
}
现在我想使用java 8实现以下目标
List<C> newListC = a.getB().getListC();
Map<Integer, String> map = new HashMap<>();
for(C c : newListC) {
map.put(c.getId,c.getName());
}
我尝试过很多次,但每次都会遇到不同的问题。 我的代码:
Optional<A> a=Optional.of(new A());
Map<Integer, String> map= a.map(A::getB)
.flatMap(b ->
b.getListC()
.stream()
.collect(Collectors.toMap(
C::getId,
C::getName
)
)
);
错误消息:
Error:(164, 33) java: incompatible types: no instance(s) of type
variable(s) U,R,A,capture#1 of ?,T,K,U exist so that
java.util.Optional<U> conforms to
java.util.Map<java.lang.Integer,java.lang.String>
提前致谢
最佳答案
虽然我遇到了一些编译错误,因为我看到了一些拼写错误,但是
尝试:
List<C> newListC= new A().getB().getListC();
Map<Integer, String> stringMap = newListC.stream()
.collect(Collectors
.toMap(C::getId, C::getName));
如果您修复了编译问题,它应该会发出与 map 的非流版本等效的结果。
关于Java 8 平面图、流、收集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36830058/