将链接的对象转换为流或集合 [英] Turn linked Objects into Stream or Collection

查看:139
本文介绍了将链接的对象转换为流或集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to iterate over a stacktrace. The stacktrace consists of throwables whose getCause() returns the next throwable. The last call to getCause() returns null. (Example: a -> b -> null)

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

I've tried to use Stream.iterable() which results in a NullPointerException, since the elements in the iterable can't be null. Here is a short demonstration of the problem:

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

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

I'm currently using a while loop to create a collection manually:

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);
  }

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

Is there a better way (shorter, more functional) to achieve this?

推荐答案

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

I think that you can do a recursive call here:

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

这篇关于将链接的对象转换为流或集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆