将链接的对象转换为流或集合

时间:2017-09-06 12:59:29

标签: java collections java-8 java-stream

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

我尝试使用Stream.iterable()导致NullPointerException,因为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);
  }

有没有更好的方法(更短,更实用)来实现这一目标?

6 个答案:

答案 0 :(得分:16)

问题是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

答案 1 :(得分:14)

我认为你可以在这里做一个递归调用:

static Stream<Throwable> process(Throwable t) {
    return t == null ? Stream.empty() : Stream.concat(Stream.of(t), process(t.getCause()));
}

答案 2 :(得分:9)

递归Stream::concat()方法在一次递归调用中提前创建整个流。在Java 9之前,懒惰的takeWhile方法不可用。

以下是一种懒惰的Java 8方法:

class NullTerminated {
    public static <T> Stream<T>  stream(T start, Function<T, T> advance) {
        Iterable<T> iterable = () -> new Iterator<T>() {
            T next = start;

            @Override
            public boolean hasNext() {
                return next != null;
            }

            @Override
            public T next() {
                T current = next;
                next = advance.apply(current);
                return current;
            }           
        };
        return StreamSupport.stream(iterable.spliterator(), false);
    }
}

用法:

Throwable b = new Throwable();
Throwable a = new Throwable(b);

NullTerminated.stream(a, Throwable::getCause).forEach(System.out::println);

更新:直接构建Iterator替换Iterable.spliterator() / Spliterator

class NullTerminated {
    public static <T> Stream<T>  stream(T start, Function<T, T> advance) {
        Spliterator<T> sp = new AbstractSpliterator<T>(Long.MAX_VALUE, Spliterator.ORDERED | Spliterator.NONNULL) {
            T current = start;
            @Override
            public boolean tryAdvance(Consumer<? super T> action) {
                if (current != null) {
                    action.accept(current);
                    current = advance.apply(current);
                    return true;
                }
                return false;
            }
        };
        return StreamSupport.stream(sp, false);
    }
}

更新2:

对于一次性,高效的最小代码实现,它将Throwable个对象链转换为Stream<Throwable>流,并立即使用所述流:

Stream.Builder<Throwable> builder = Stream.builder();
for(Throwable t = a; t != null; t = t.getCause())
    builder.accept(t);
builder.build().forEach(System.out::println);

这样做的缺点是非延迟(在流构建时遍历整个链),但避免了递归和Stream.concat()的低效率。

答案 3 :(得分:5)

我可以通过Spliterator

选择其他选项
static Stream<Throwable> process(Throwable t) {

    Spliterator<Throwable> sp = new AbstractSpliterator<Throwable>(100L, Spliterator.ORDERED) {

        Throwable inner = t;

        @Override
        public boolean tryAdvance(Consumer<? super Throwable> action) {
            if (inner != null) {
                action.accept(inner);
                inner = inner.getCause();
                return true;
            }

            return false;
        }
    };

    return StreamSupport.stream(sp, false);
}

答案 4 :(得分:3)

如果我理解正确,您可以创建Stream种子root(您的头部Throwable在链表中)。 UnaryOperator采取的是下一个Throwable。例如:

Stream.iterate(root, Throwable::getNext)
         .takeWhile(node -> node != null)
         .forEach(node -> System.out.println(node.getCause()));

答案 5 :(得分:2)

这究竟出了什么问题?

while (exception) {
    System.out.println(exception); //or whatever you want to do
    exception = exception.getCause();
}

“功能性更强”没有意义。功能风格只是一种工具,在这里显然是不合适的。

相关问题