These methods transform a stream’s elements into an IntStream, LongStream, or DoubleStream respectively, which are specialized streams for handling primitive data types efficiently. By using these methods, you can avoid the overhead associated with boxing and unboxing objects.

mapToInt
Transforms elements to an IntStream.
List<String> numbersAsString = Arrays.asList("10000000000", "20000000000");
LongStream longStream = numbersAsString.stream()
.mapToLong(Long::parseLong);
longStream.forEach(System.out::println);
This example converts a list of strings to an IntStream of integers.
mapToLong
Transforms elements to a LongStream.
List<String> numbersAsString = Arrays.asList("10000000000", "20000000000");
LongStream longStream = numbersAsString.stream()
.mapToLong(Long::parseLong);
longStream.forEach(System.out::println);
Here, each string is parsed into a long value, producing a LongStream.
mapToDouble
Transforms elements to a DoubleStream.
List<String> numbersAsString = Arrays.asList("1.5", "2.5", "3.5");
DoubleStream doubleStream = numbersAsString.stream()
.mapToDouble(Double::parseDouble);
doubleStream.forEach(System.out::println);
This operation converts strings to a DoubleStream of floating-point numbers.
Flat Mapping Operations: flatMapToInt, flatMapToLong, and flatMapToDouble
These operations are used when each element of a stream should be mapped to a stream of primitive values (IntStream, LongStream, or DoubleStream). They flatten the resulting streams into a single stream.
flatMapToInt
Maps each element to an IntStream and flattens the result.
Stream<String> strings = Stream.of("1,2,3", "4,5");
IntStream intStream = strings.flatMapToInt(s -> Arrays.stream(s.split(","))
.mapToInt(Integer::parseInt));
intStream.forEach(System.out::println);
In this example, each string containing numbers separated by commas is split, parsed into integers, and flattened into a single IntStream.
flatMapToLong
Similar to flatMapToInt, flatMapToLong produces a LongStream.
Stream<String> strings = Stream.of("10000000000,20000000000", "30000000000");
LongStream longStream = strings.flatMapToLong(s -> Arrays.stream(s.split(","))
.mapToLong(Long::parseLong));
longStream.forEach(System.out::println);
This maps each string to a LongStream of long values.
flatMapToDouble
Maps each element to a DoubleStream and flattens the result.
Stream<String> strings = Stream.of("1.1,2.2", "3.3,4.4");
DoubleStream doubleStream = strings.flatMapToDouble(s -> Arrays.stream(s.split(","))
.mapToDouble(Double::parseDouble));
doubleStream.forEach(System.out::println);
Post a Comment