Close

Java 8 Streams - Stream.map Examples

Java 8 Streams Java Java API 


Interface:

java.util.stream.Stream

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

Method:

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

This intermediate operation, returns a stream 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.stream.Stream;

public class MapExample2 {

public static void main(String... args) {
String[] s = {"one", "two", "three", "four"};
Stream<String> stringStream = Stream.of(s);
Stream<Character> charStream = stringStream.map(e -> e.charAt(0));
charStream.forEach(System.out::println);
}
}

Output

o
t
t
f




package com.logicbig.example.stream;

import java.util.stream.Stream;

public class MapExample {

public static void main(String... args) {
String[] s = {"one", "two", "three", "four"};
Stream<String> stringStream = Stream.of(s);
Stream<Integer> intStream = stringStream.map(String::length);
intStream.forEach(System.out::println);
}
}

Output

3
3
5
4




This example shows that accessing external state from map method, can lead to non-determinist result.

package com.logicbig.example;

import java.util.HashSet;
import java.util.Set;
import java.util.stream.IntStream;

public class StatefulExample {

public static void main (String[] args) {
for (int i = 0; i < 10; i++) {
Set<Integer> seen = new HashSet<>();
IntStream stream = IntStream.of(1, 2, 1, 2, 3, 4, 4, 5);
int sum = stream.parallel().map(
//stateful behavioral parameter.
e -> {
try {//making it bit slow for more thread
//interference changes
Thread.sleep(10);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
if (seen.add(e))
return e;
else
return 0;
}).sum();
System.out.println(sum);

}
}
}

Output

15
15
15
17
17
20
15
15
16
16
Original Post




This example shows alternative way to do the same thing so avoiding statefulness from an intermediate function.

package com.logicbig.example;

import java.util.stream.IntStream;

public class StatefulFixExample {

public static void main (String[] args) {
for (int i = 0; i < 10; i++) {
IntStream stream = IntStream.of(1, 2, 1, 2, 3, 4, 4, 5);
int sum = stream.parallel().distinct().sum();
System.out.println(sum);
}
}
}

Output

15
15
15
15
15
15
15
15
15
15
Original Post




See Also