如何在 Java 8 中将此 while 循环转换为流?
Location toTest = originalLocation;
while(true){
toTest = toTest.getParentLocation();
if (toTest==null) {
break;
}
parents.add(toTest);
}
假设 Location 沿着 :
@Data
public class Location{
private String name;
private Location parentLocation;
}
看起来应该是:
Stream.iterate(location, l -> l.getParentLocation()).collect(Collectors.toList());
但是这给了我一个 NullPointerException。我假设是 getParentLocation()
返回 null...
有人能帮忙吗?
最佳答案
JDK9解决方案:
Stream.iterate(location, Objects::nonNull, Location::getParentLocation)
.collect(Collectors.toList());
关于java - 祖先列表作为流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51621419/