{

Java8 - Stream map methods with examples


java8 features - Stream map with examples

What is a Stream map in java8?

map()method map the object to other objects of the same type or different type.

It is an intermediate operation in processing stream of objects

they called lazily and accept input as a function and output stream of objects which contains results by applying a function to each element of a stream.

Following is a Syntax

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

map method takes Function as input. The function is a functional interface with one abstract method.
Takes Input of Type T and Return Output of Type R.

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  

java8 provides three types of map methods which are used to handle int, long, and Double values.

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

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

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

  • It accepts ToLongFunction as an argument and returns LongStream.
  • ToLongFunction is a functional Interface with a single abstract method that takes input long values and outputs result.
  • LongStream is a long version of the Stream class.
  • Each element of a 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 this tutorial, Learned the Stream map method with examples and methods explanation.

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.