流的祖先列表

时间:2018-07-31 20:17:32

标签: java java-8

如何在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 ...

任何人都可以帮忙吗?

3 个答案:

答案 0 :(得分:4)

JDK9解决方案:

Stream.iterate(location, Objects::nonNull, Location::getParentLocation)
      .collect(Collectors.toList());

答案 1 :(得分:2)

您正在寻找的是来自Java-9的takeWhile

...takeWhile( x -> x != null).collect...

答案 2 :(得分:2)

使用Java 9中添加的iterate​(T seed, Predicate<? super T> hasNext, UnaryOperator<T> next)重载:

Stream.iterate(location, l -> l != null, l -> l.getParentLocation())
      .collect(Collectors.toList());

使用相同的方法引用:

Stream.iterate(location, Objects::nonNull, Location::getParentLocation)
      .collect(Collectors.toList());