mapMulti
mapMulti is a flexible version of flatMap, allowing more control over the mapping and the elements’ addition to the output.
Stream.of(1, 2, 3).<String>mapMulti((number, consumer) -> {
consumer.accept(number + "a");
consumer.accept(number + "b");
}).forEach(System.out::println);
This example demonstrates generating two strings from each integer and adding them to the resulting stream.
mapMultiToInt, mapMultiToLong, and mapMultiToDouble
These are specialized versions of mapMulti for primitive streams.
mapMultiToInt
Similar to mapMulti but for IntStream.
Stream.of("1,2", "3,4").mapMultiToInt((s, consumer) -> {
Arrays.stream(s.split(",")).mapToInt(Integer::parseInt).forEach(consumer);
}).forEach(System.out::println);
This example splits each string and maps them to integers, collecting them into an IntStream.
mapMultiToLong
Used for generating a LongStream.
Stream.of("10000000000,20000000000").mapMultiToLong((s, consumer) -> {
Arrays.stream(s.split(",")).mapToLong(Long::parseLong).forEach(consumer);
}).forEach(System.out::println);
It splits strings and maps the parts to a LongStream.
mapMultiToDouble
For creating a DoubleStream.
Stream.of("1.1,2.2").mapMultiToDouble((s, consumer) -> {
Arrays.stream(s.split(",")).mapToDouble(Double::parseDouble).forEach(consumer);
}).forEach(System.out::println);
Here, each input string is split and converted into a DoubleStream.
These operations offer greater flexibility and efficiency, particularly when dealing with primitive data types or complex data transformations. They enhance the Java Streams API by providing more granular control over data processing, allowing for more concise and expressive code.
Post a Comment