我有对象的列表,其中一些可以收藏。我想获得普通对象流。
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);
我还检查了example它展示了如何使用递归函数,它变平的集合。然而,在该示例.collect(Collectors.toList());
用于保持中间结果。 Collectors.toList()
是终端操作,这将开始处理流的时候了。我想获得一个流,我以后可以重复上。
我同意的意见,这是一个可怕的想法有不同性质的物体组成的流。我只写了简单这个问题。在现实生活中,它可以是我听不同的事件,以及处理从输入流一些业务对象,他们中的一些可以发送对象,其他的流 - 只是单个对象。
我们可以递归得到嵌套stream
如果被穿越的对象是Collection
的一个实例。
public static void main(String args[]) {
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))));
List<Object> list = objects.stream().flatMap(c -> getNestedStream(c)).collect(Collectors.toList());
}
public static Stream<Object> getNestedStream(Object obj) {
if(obj instanceof Collection){
return ((Collection)obj).stream().flatMap((coll) -> getNestedStream(coll));
}
return Stream.of(obj);
}
class Loop {
private static Stream<Object> flat(Object o) {
return o instanceof Collection ?
((Collection) o).stream().flatMap(Loop::flat) : Stream.of(o);
}
public static void main(String[] args) {
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))));
List<Object> flat = flat(objects).collect(Collectors.toList());
System.out.println(flat);
}
}
请注意List.of(null)
抛出NPE。
请注意,这是可能的定义字段中的递归方法:
public class Test {
static Function<Object,Stream<?>> flat=
s->s instanceof Collection ? ((Collection<?>)s).stream().flatMap(Test.flat) : Stream.of(s);
public static void main(String[] args) {
objects.stream().flatMap(flat).forEach(System.out::print);
}
}