Yan*_*ski 17 java java-stream flatmap
我有一个对象列表,其中一些可以是集合.我想得到一个普通物体流.
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))));
Run Code Online (Sandbox Code Playgroud)
我想获得一个包含元素的流.
1, 2, "SomeString", 3, 4, 5, 6, 7, "a", "b", "c", 8, 9, 10
Run Code Online (Sandbox Code Playgroud)
我试过了
Function<Object, Stream<Object>> mbjectToStreamMapper = null; //define it. I have not figured it out yet!
objects.stream().flatMap(ObjectToStreamMapper).forEach(System.out::println);
Run Code Online (Sandbox Code Playgroud)
我还检查了一个示例,该示例演示了如何使用递归函数来展平集合.但是,在此示例中.collect(Collectors.toList());
用于保持中间结果.Collectors.toList()
是一个终端操作,它将立即开始处理流.我想得到一个流,我可以稍后重复.
我同意评论,有一个由不同性质的对象组成的流是一个可怕的想法.我只是为了简单起见写了这个问题.在现实生活中,我可以听到不同的事件,并从传入的流处理一些业务对象,其中一些可以发送对象流,其他 - 只是单个对象.
Ada*_*ion 16
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);
}
}
Run Code Online (Sandbox Code Playgroud)
请注意List.of(null)
抛出NPE.
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);
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
635 次 |
最近记录: |