平面图嵌套集合

我有一个对象列表,其中一些可以是集合。我想得到一个普通对象流。


List<Object> objects = List.of(1, 2, "SomeString", List.of(3, 4, 5, 6), 

    7, List.of("a", "b", "c"),

    List.of(8, List.of(9, List.of(10))));

我想获得一个带有元素的流。


1, 2, "SomeString", 3, 4, 5, 6, 7, "a", "b", "c", 8, 9, 10

我努力了


Function<Object, Stream<Object>> mbjectToStreamMapper = null; //define it. I have not figured it out yet!

objects.stream().flatMap(ObjectToStreamMapper).forEach(System.out::println);

我还检查了一个示例,该示例显示了如何使用递归函数来展平集合。但是,在此示例中.collect(Collectors.toList());用于保留中间结果。Collectors.toList()是一个终端操作,它将立即开始处理流。我想获得一个流,我可以稍后对其进行迭代。


更新

我同意评论,拥有一个由不同性质的对象组成的流是一个糟糕的主意。为了简单起见,我只是写了这个问题。在现实生活中,我可能会监听不同的事件,并处理来自传入流的一些业务对象,其中一些可以发送对象流,其他的 - 只是单个对象。


大话西游666
浏览 166回答 3
3回答

牛魔王的故事

class Loop {&nbsp; &nbsp; private static Stream<Object> flat(Object o) {&nbsp; &nbsp; &nbsp; &nbsp; return o instanceof Collection ?&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ((Collection) o).stream().flatMap(Loop::flat) : Stream.of(o);&nbsp; &nbsp; }&nbsp; &nbsp; public static void main(String[] args) {&nbsp; &nbsp; &nbsp; &nbsp; List<Object> objects = List.of(1, 2, "SomeString", List.of( 3, 4, 5, 6),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 7, List.of("a", "b", "c"), List.of(8, List.of(9, List.of(10))));&nbsp; &nbsp; &nbsp; &nbsp; List<Object> flat = flat(objects).collect(Collectors.toList());&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(flat);&nbsp; &nbsp; }}请注意List.of(null)抛出 NPE。

慕容森

如果被遍历stream的对象是Collection.public static void main(String args[]) {&nbsp; &nbsp; &nbsp; &nbsp;List<Object> objects = List.of(1, 2, "SomeString", List.of(3, 4, 5, 6),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 7, List.of("a", "b", "c"),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; List.of(8, List.of(9, List.of(10))));&nbsp; &nbsp; &nbsp; &nbsp;List<Object> list = objects.stream().flatMap(c -> getNestedStream(c)).collect(Collectors.toList());}public static Stream<Object> getNestedStream(Object obj) {&nbsp; &nbsp; if(obj instanceof Collection){&nbsp; &nbsp; &nbsp; &nbsp; return ((Collection)obj).stream().flatMap((coll) -> getNestedStream(coll));&nbsp; &nbsp; }&nbsp; &nbsp; return Stream.of(obj);}

慕桂英4014372

注意,可以在字段中定义递归方法:public class Test {&nbsp; static Function<Object,Stream<?>> flat=&nbsp; &nbsp; s->s instanceof Collection ? ((Collection<?>)s).stream().flatMap(Test.flat) : Stream.of(s);&nbsp; public static void main(String[] args) {&nbsp; &nbsp; objects.stream().flatMap(flat).forEach(System.out::print);&nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java