Java 8 Stream map Sample

Java 8 Streams map operation returns a stream base on the results of applying the given function to the elements in this stream. We can use Stream.map() function for transforming the objects based on the input method.

The sample Java 8 Stream map() code below converts all string elements into upper case. Before Java 8, what would have been done in a few lines, is now done in a single line.

Java 8 Stream map Sample Code

The map() stream operation returns a stream with all upper case elements and the foreach() operation prints out the elements.

public class jcdStreamMapSample {
 
    public static void main(String a[]) {
        List<String> widgets = Arrays.asList("widgetA", "widgetB", "widgetC", "widgetD", "widgetE");
        widgets.stream().map(String::toUpperCase).forEach(System.out::println);
    }
}


Java 8 Stream map Output

WIDGETA
WIDGETB
WIDGETC
WIDGETD
WIDGETE


The Java 8 Stream map() operation is an intermediate operation, meaning this operation will return a new stream. The map() method is a stateless operation, meaning that it retains no state from previously seen element when processing a new element.

Add a Comment

Your email address will not be published. Required fields are marked *