有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

作为流的java祖先列表

如何在Java8中将这个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) 个答案

  1. # 1 楼答案

    使用Java 9中添加的^{}重载:

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

    使用相同的方法引用:

    Stream.iterate(location, Objects::nonNull, Location::getParentLocation)
          .collect(Collectors.toList());
    
  2. # 2 楼答案

    JDK9解决方案:

    Stream.iterate(location, Objects::nonNull, Location::getParentLocation)
          .collect(Collectors.toList());
    
  3. # 3 楼答案

    您要查找的是java-9中的takeWhile

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