Java 8 Map Function Examples

The map is a well known functional programming concept which is incorporated into Java 8. Map is a function defined in java.util.stream.Streams class, which is used to transform each element of the stream. Because of this property, you can use Map in Java 8 to transform a Collection, List, Set or Map. For example, if you have a list of String and you want to convert all of them into upper case, how will you do this? Prior to Java 8, there is no function to do this. You had to iterate through List using a for loop or foreach loop and transform each element. In Java 8, you get the stream, which allows you to apply many functional programming operators like the map, reduce and filter. By using Map function, you can apply any function to every element of Collection. It can be any predefined function or a user-defined function. You not only can use the lambda expression but also, you can also use method references.

Some examples of Map in Java 8 is to convert a list of integers and then square of each number. The map function is also an intermediate operation and it returns a stream of transformed element.

Stream API also provides methods like mapToDouble(), mapToInt(), and mapToLong() which returns DoubleStream, IntStream and LongStream, which are specialized stream for double, int and long data types.

You can collect the result of transformation by using Collectors class, which provides several method to collect the result of transformation into List, Set or any Collection.




How to use Map in Java 8

As I said, Map function in Java 8 stream API is used to transform each element of Collection be it, List, Set or Map. In this Java 8 tutorial, we have used Map function for two examples, first to convert each element of List to upper case, and second to square each integer in the List. By the way, this is just tip of the iceberg of what you can do with Java 8. See my Java 8 Stream Examples to learn how to filter element in the collection in Java 8.

You can also check out Java SE 8 for Really Impatient from Cay S. Horstmann for few more examples. It's one of the books I personally prefer to learn Java 8.

How to use map function in Java 8

Now let's see an example to convert each element of a List to upper case using map function. Once again, map applies a mapping function on each element of Stream and stores result in another Stream.

How to use map() function in Java 8

package test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import static java.util.stream.Collectors.toList;

/**
 * Java 8 example to convert each element of List into upper case. You can use
 * Map function of Java 8 to transform each element of List or any collection.
 * @author Javin
 */
public class Java8MapExample {

    public static void main(String args[]) {
       List<String> cities = Arrays.asList("London", "HongKong", "Paris", "NewYork");
       System.out.println("Original list : " + cities);
       System.out.println("list transformed using Java 8 :" + transform(cities));
       System.out.println("list transformed using loop before Java 8 : " + beforeJava8(cities));
       
       
       // You can even on the fly tranform Collection in Java using Map function
       // let's transform a List of integers to square each element
       List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
       List<Integer> squares = numbers.stream().map( i -> i*i).collect(Collectors.toList());
       System.out.println("original list of numbers : " + numbers);
       System.out.println("transformed list of integers using Map in Java 8 : " + squares);

    }

    /**
     * This is how you convert all elements of list into upper case using loop before Java 8
     * @param listOfString
     * @return List with each element converted into upper case
     */
    public static List<String> beforeJava8(List<String> listOfString) {
        List<String> coll = new ArrayList<>();
        for (String str : listOfString) {
            coll.add(str.toUpperCase());
        }
        return coll;
    }

    /**
     * You can use Java 8 map function to transform each element of list
     * @param listOfString
     * @return list of elements with upper case
     */
    public static List<String> transform(List<String> listOfString) {
        return listOfString.stream() // Convert list to Stream
                .map(String::toUpperCase) // Convert each element to upper case
                .collect(toList()); // Collect results into a new list
    }

}

Output
run:
Original list : [London, HongKong, Paris, NewYork]
list transformed using Java 8 :[LONDON, HONGKONG, PARIS, NEWYORK]
list transformed using loop before Java 8 : [LONDON, HONGKONG, PARIS, NEWYORK]
original list of numbers : [1, 2, 3, 4, 5, 6, 7, 8, 9]
transformed list of integers using Map in Java 8 : [1, 4, 9, 16, 25, 36, 49, 64, 81]
BUILD SUCCESSFUL (total time: 0 seconds)


That's all about how you transform each element of List in Java 8 using Map function. It's tremendously useful and once you start using it, you will never look back. I found Java 8 really interesting, you will love to try it out. I really like a combination of lambda expression and Streams and solving problems without loops.

How to use Map function in Java 8


If you like this article and hungry for more Java 8 tutorials, check these tutorials
  • 10 ways to use Lambda expression in Java 8 (read here)
  • Free Java 8 tutorials and Books (read book)
  • Top 10 tutorials to Learn Java 8 (read more)
  • How to use Lambda Expression in Place of Anonymous class (read tutorial)
  • How to use Default method in Java 8. (see example)
  • Java 8 Comparator Example (see here)

Recommended Books to Learn Java 8

If you are new to Java 8 world and would like to learn Java 8 from scratch, I suggest you take a look at any of following books. These are some of the best books currently available in market on Java 8:


2 comments:

  1. Nice article with good example

    ReplyDelete
  2. It's very detail post. Thanks for you helpful!

    ReplyDelete