Java8 - Stream map methods with examples

In this blog post, we’ll delve into the intricacies of the map() method in Java 8 Streams.

Introduction to map() in java 8

The map() method is employed to transform objects into other objects of the same or different types within a Stream. It serves as an intermediate operation in stream processing, allowing for the application of a function to each element of the stream.

This operation is executed lazily, meaning it is invoked only when needed, and it produces a stream of objects containing the results of applying the function to each element.

Following is a Syntax

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

Here, the map method takes a Function as input. The Function interface is a functional interface with one abstract method, accepting input of type T and returning output of type R.

Let’s explore some examples of using the map() method in Java 8 Streams.

java Map Filter Examples

It is an example for List of String which contains numbers as input and output returns even numbers.

  • Created a List of strings
  • Created Stream from List
  • Call map() method with a lambda expression to iterate stream of elements
  • Apply filter to each element to check event number
  • Finally, terminal operation collect to convert the stream to List
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Test {
    public static void main(String[] args) {
        List<String> listStringNumbers = Arrays.asList("11", "12", "31", "41", "15", "16");
        System.out.println(listStringNumbers);
        List<Integer> eventNumbers = listStringNumbers.stream()
                .map(s -> Integer.valueOf(s))
                .filter(number -> number % 2 == 0)
                .collect(Collectors.toList());
        System.out.println(eventNumbers);
    }
}

Output:

[11, 12, 31, 41, 15, 16]
[12, 16]

How to convert Map to List using streams?

It is an example of Converting hashmap to a custom java object. Using lambda expressions with the stream, iterate hash map elements and construct objects.

import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class MapExample {
    public static void main(String[] args) {
        Map<String, String> map = new HashMap<>();
        map.put("1", "Kiran");
        map.put("12", "Ram");
        map.put("13", "John");
        map.put("5", "Frank");
        List<MyObject> listOfObjects = map.entrySet().stream().sorted(Comparator.comparing(e -> e.getKey()))
                .map(e -> new MyObject(e.getKey(), e.getValue())).collect(Collectors.toList());

        listOfObjects.forEach(l -> System.out.println("Id: " + l.getId() + ", Name: " + l.getName()));
    }
}
class MyObject {
    private String id;
    private String name;

    public MyObject(String id, String name) {
        this.id = id;
        this.name = name;
    }
    public String getId() {
        return id;
    }
    public String getName() {
        return name;
    }
}

Output:

Id: 1, Name: Kiran
Id: 12, Name: Ram
Id: 13, Name: John
Id: 5, Name: Frank

How to convert List of String to uppercase or lowercase?

Created a Stream from List and calling map on each string, convert and output to console.

import java.util.Arrays;
import java.util.List;

public class Test {
    public static void main(String[] args) {
        List<String> listString= Arrays.asList("one", "two", "three", "four", "five");
        listString.stream().map(String::toUpperCase).forEach(System.out::println);
    }
}

Output:

ONE
TWO
THREE
FOUR
FIVE

Java 8 provides three types of map methods tailored for handling int, long, and Double values.

mapToInt - IntStream mapToInt ( ToIntFunction<? super T> mapper ):

  • Accepts a ToIntFunction as a parameter and returns an IntStream.
  • ToIntFunction is a functional interface with a single abstract method that accepts integer values and generates a result.
  • IntStream is the integer version of the Stream class.
  • Each element of the stream is applied to the function.

mapToLong - LongStream mapToLong ( ToLongFunction<? super T> mapper ):

  • Accepts a ToLongFunction as an argument and returns a LongStream.
  • ToLongFunction is a functional interface with a single abstract method that takes long values as input and outputs a result.
  • LongStream is the long version of the Stream class.
  • Each element of the stream is applied to the function.

mapToDouble - DoubleStream mapToDouble ( ToDoubleFunction<? super T> mapper ):

  • It accepts ToDoubleFunction as an argument and returns DoubleStream.
  • ToDoubleFunction is a functional interface with a single abstract method that takes input double values and outputs results.
  • DoubleStream is a double version of the Stream class.
  • Each element of a stream is applied to the function.

Conclusion

In conclusion, this tutorial has provided insights into the map() method in Java 8 Streams, along with practical examples and explanations. With the map() method, developers can easily transform objects within a stream, enhancing the flexibility and functionality of stream operations.