FlatMap on an Array or Stream
$ jshell
jshell> System.out.println(Stream.of(1, 2, 3).map((x) -> Arrays.asList(-x, x)).collect(Collectors.toList()));
[[-1, 1], [-2, 2], [-3, 3]]
jshell> System.out.println(Stream.of(1, 2, 3).flatMap((x) -> Stream.of(-x, x)).collect(Collectors.toList()));
[-1, 1, -2, 2, -3, 3]$ yarn add ts-node typescript
$ echo '{ "compilerOptions": {"lib": ["es2019"]} }' >tsconfig.json
$ node_modules/.bin/ts-node
> [1, 2, 3].map((x) => [-x, x])
[ [ -1, 1 ], [ -2, 2 ], [ -3, 3 ] ]
> [1, 2, 3].flatMap((x) => [-x, x])
[ -1, 1, -2, 2, -3, 3 ]Stream.of(0, 1, 2, 3).map((x) -> x.equals(0) ? Collections.emptyList() : Arrays.asList(-x, x)).collect(Collectors.toList())
==> [[], [-1, 1], [-2, 2], [-3, 3]]
Stream.of(0, 1, 2, 3).flatMap((x) -> x.equals(0) ? Stream.empty() : Stream.of(-x, x)).collect(Collectors.toList())
==> [-1, 1, -2, 2, -3, 3]> [0, 1, 2, 3].map((x) => x == 0 ? [] : [-x, x])
[ [], [ -1, 1 ], [ -2, 2 ], [ -3, 3 ] ]
> [0, 1, 2, 3].flatMap((x) => x == 0 ? [] : [-x, x])
[ -1, 1, -2, 2, -3, 3 ]Last updated