zw-habbit
public static void main(String[] args) {

        List<C> listC1 = new ArrayList<C>(
                Arrays.asList(new C("c11"), new C("c12"), new C("c13"), new C("c14"), new C("c15"))
        );
        List<C> listC2 = new ArrayList<C>(
                Arrays.asList(new C("c21"), new C("c22"), new C("c23"), new C("c24"), new C("c25"))
        );
        List<C> listC3 = new ArrayList<C>(
                Arrays.asList(new C("c31"), new C("c32"), new C("c33"), new C("c34"), new C("c35"))
        );
        List<C> listC4 = new ArrayList<C>(
                Arrays.asList(new C("c41"), new C("c42"), new C("c43"), new C("c44"), new C("c45"))
        );

        List<B> listB1 = new ArrayList<>(
                Arrays.asList(new B("b11",listC1), new B("b12", listC2))
        );
        List<B> listB2 = new ArrayList<>(
                Arrays.asList(new B("b21",listC3), new B("b22", listC4))
        );
        List<A> listA = new ArrayList<>(
                Arrays.asList(new A("a11", listB1), new A("a21", listB2))
        );
        List<Stream<Stream<C>>> collect = listA.stream().map(a -> a.getListB().stream().map(b -> b.getListC().stream().map(c -> c))).collect(Collectors.toList());

        List<C> collect1 = listA.stream().flatMap(a -> a.getListB().stream().flatMap(b -> b.getListC().stream())).collect(Collectors.toList());
    }

在Stream中,flatMap能实现将各层的Stream铺平,得到最底层的List集合List,而map只能得到Stream流的嵌套对象最终只能转换成List<List<List>>的形式

<R> Stream<R> map(Function<? super T, ? extends R> mapper);
<R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper);

从源码中可以看出,map和flapMap本质上都是函数式接口Function的实现, 输入都是T,但是map会将返回值封装成独立Stream(类似于A中有个ListB,最后map的结果得到的是多个Stream(B)),而flapMap会将多个Stream(B)合并成一个Stream(B)
Mono中的实现也类似

public final <R> Mono<R> map(Function<? super T, ? extends R> mapper) {
		if (this instanceof Fuseable) {
			return onAssembly(new MonoMapFuseable<>(this, mapper));
		}
		return onAssembly(new MonoMap<>(this, mapper));
	}
	
public final <R> Mono<R> flatMap(Function<? super T, ? extends Mono<? extends R>>
			transformer) {
		return onAssembly(new MonoFlatMap<>(this, transformer));
	}

image

image

分类:

技术点:

相关文章:

  • 2022-12-23
  • 2021-08-14
  • 2021-11-19
  • 2021-06-23
  • 2021-12-25
  • 2021-11-19
  • 2021-11-19
  • 2021-11-19
猜你喜欢
  • 2021-11-19
  • 2021-05-30
  • 2021-11-19
  • 2021-11-19
  • 2021-11-19
  • 2021-09-05
相关资源
相似解决方案