Tuesday, August 28, 2018

Java8 - Learn Stream map methods with examples

Stream map method introduction

map() method map the object to others object of the same type or different type. It is 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

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

Map Filter examples

This is an example for List of String which contains numbers as input and output return even numbers.
  • Created 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 

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 is
[11, 12, 31, 41, 15, 16]
[12, 16]

How to convert Map to List using streams?

This is an example for Converting hashmap to a custom java object.
Using lambda expressions with the stream, iterate hash map elements an construct object.

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 is
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.
List<String> listString= Arrays.asList("one", "two", "three", "four", "five");
listString.stream().map(String::toUpperCase).forEach(System.out::println);
Output is
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 which takes input long values and outputs result.LongStream is a long version of 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. is ToDoubleFunction a functional Interface with a single abstract method which takes input double values and outputs result.DoubleStream is a double version of Stream class. Each element of a stream is applied to the function.

Related article


EmoticonEmoticon