我有一个对象列表,其中一些可以是集合。我想要一条普通的物体流。
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()是一个终端操作,它将立即开始处理流。我想得到一个流,我可以在以后进行迭代。
更新
我同意大家的意见,有一条由不同性质的物体组成的小溪是个可怕的想法。我写这个问题只是为了简单。在现实生活中,我可以监听不同的事件,并处理来自传入流的一些业务对象,其中一些可以发送对象流,其他--只是单个对象。
发布于 2019-02-03 16:22:54
如果要遍历的对象是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);
}发布于 2019-02-03 16:13:05
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。
发布于 2019-02-03 17:13:26
注意,可以在字段中定义递归方法:
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);
}
}https://stackoverflow.com/questions/54504572
复制相似问题