如何在Java 8中将此while循环转换为流?

    Location toTest = originalLocation;
    while(true){
        toTest = toTest.getParentLocation();
        if (toTest==null) {
            break;
        }
        parents.add(toTest);
    }


假设位置沿以下方向:

@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());

07-23 22:04