Close

Java 8 Streams - Stream.mapToInt Examples

Java 8 Streams Java Java API 


Interface:

java.util.stream.Stream

java.lang.AutoCloseableAutoCloseablejava.util.stream.BaseStreamBaseStreamjava.util.stream.StreamStreamLogicBig

Method:

IntStream mapToInt(ToIntFunction<? super T> mapper)

This intermediate operation returns a IntStream consisting of the results of applying the given mapper function to the elements of this stream.


Examples


package com.logicbig.example.stream;

import java.util.IntSummaryStatistics;
import java.util.stream.IntStream;
import java.util.stream.Stream;

public class MapToIntExample {

public static void main(String... args) {
String[] s = {"one", "two", "three", "four"};
Stream<String> stringStream = Stream.of(s);
IntStream intStream = stringStream.mapToInt(e -> e.length());
IntSummaryStatistics stats = intStream.peek(System.out::println)
.summaryStatistics();
System.out.println(stats);
}
}

Output

3
3
5
4
IntSummaryStatistics{count=4, sum=15, min=3, average=3.750000, max=5}




package com.logicbig.example;

import java.util.Arrays;
import java.util.stream.Stream;

/**
* Even though this is thread safe, but the result is non-deterministic
*/
public class SideEffectWrongUse2Fix {
public static void main(String[] args) {

int[] lengths = Stream.of("Banana", "Pear", "Apple")
.peek(SideEffectWrongUse2Fix::longTask)//applying side effect
.parallel()
.mapToInt(s -> s.length())
.toArray();
System.out.println(Arrays.toString(lengths));
}

private static void longTask(String s) {
try {//some stateless task simulation. e.g. sending email
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

Output

[6, 4, 5]
Original Post




This example also shows the wrong use of side effect.

package com.logicbig.example;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Stream;

/**
* Even though this is thread safe, but the result is non-deterministic
*/
public class SideEffectWrongUse2 {
public static void main (String[] args) {
List<Integer> lengths = Collections.synchronizedList(new ArrayList<>());
Stream.of("Banana", "Pear", "Apple")
.peek(SideEffectWrongUse2::longTask)//applying side effect
.parallel()
.mapToInt(s -> s.length())
.forEach(lengths::add);//collecting via side effect
// updating state
System.out.println(lengths);
}

private static void longTask (String s) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

Output

[4, 5, 6]
Original Post




See Also