gpt4 book ai didi

java - 将链接的对象变成流或集合

转载 作者:IT老高 更新时间:2023-10-28 20:56:38 26 4
gpt4 key购买 nike

我想遍历堆栈跟踪。堆栈跟踪由其 getCause() 返回下一个 throwable 的 throwable 组成。最后一次调用 getCause() 返回 null。 (例如:a -> b -> null)

我尝试使用导致 NullPointerException 的 Stream.iterable(),因为 iterable 中的元素不能为空。以下是该问题的简短演示:

  public void process() {
Throwable b = new Throwable();
Throwable a = new Throwable(b);
Stream.iterate(a, Throwable::getCause).forEach(System.out::println);
}

我目前正在使用 while 循环手动创建集合:

public void process() {
Throwable b = new Throwable();
Throwable a = new Throwable(b);

List<Throwable> list = new ArrayList<>();
Throwable element = a;
while (Objects.nonNull(element)) {
list.add(element);
element = element.getCause();
}
list.stream().forEach(System.out::println);
}

有没有更好的方法(更短、更实用)来实现这一点?

最佳答案

问题是 Stream.iterate 中缺少停止条件。在 Java 9 中,您可以使用

Stream.iterate(exception, Objects::nonNull, Throwable::getCause)

相当于 Java 9 的

Stream.iterate(exception, Throwable::getCause)
.takeWhile(Objects::nonNull)

Stream.iterateStream.takeWhile .

由于 Java 8 中不存在此功能,因此需要一个反向端口:

public static <T> Stream<T>
iterate​(T seed, Predicate<? super T> hasNext, UnaryOperator<T> next)
{
Objects.requireNonNull(next);
Objects.requireNonNull(hasNext);
return StreamSupport.stream(
new Spliterators.AbstractSpliterator<T>(Long.MAX_VALUE, Spliterator.ORDERED) {
T current = seed;
int state;
public boolean tryAdvance(Consumer<? super T> action) {
Objects.requireNonNull(action);
T value = current;
if(state > 0) value = next.apply(value);
else if(state == 0) state = 1;
else return false;
if(!hasNext.test(value)) {
state = -1;
current = null;
return false;
}
action.accept(current = value);
return true;
}
},
false);
}

语义与 Java 9 的 Stream.iterate 相同:

MyStreamFactory.iterate(exception, Objects::nonNull, Throwable::getCause)
.forEach(System.out::println); // just an example

关于java - 将链接的对象变成流或集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46075928/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com