【发布时间】:2018-07-31 20:17:32
【问题描述】:
如何在 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...
谁能帮忙?
【问题讨论】:
-
什么是
location,什么是parents? -
该代码不会永远循环吗?我的意思是,
location永远不会更新,我认为它不是有状态的,所以getParentLocation()总是返回相同的值。我认为您需要在循环结束时使用location = l;。 -
是的.. doh。让我更新一下。
-
while ((location = location.getParentLocation()) != null) parents.add(location);呢? -
当然,是的。如何在 java 8 中将其转换为流?