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 by applying a function to each element. 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 the 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 method references.

Some examples of Map in Java 8 is to convert a list of integers and then the 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 the Collectors class, which provides several methods to collect the result of transformation into List, Set or any Collection.

Even though Java is moving really fast and we are already in Java 11, still a lot of developers has to learn Java 8, particularly the functional programming aspect. If you think that your Java 8 skills are not at par or you want to improve yourself, I suggest you join a comprehensive Java course like The Complete Java MasterClass. It covers everything you need to know and also recently updated for Java 11.





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. It's packed with many useful features and API enhancements like methods to join Strings, a new Date and Time API, Default methods and much.

For a complete Java 8 learning, I suggest you to check out What's New in Java 8, one of the courses I have used 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, the 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.


Further Learning
The Complete Java MasterClass
Java SE 8 New Features
From Collections to Streams in Java 8 Using Lambda Expressions


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 the book)
  • Top 10 tutorials to Learn Java 8 (read more)
  • How to use Lambda Expression in Place of Anonymous class (read the tutorial)
  • How to use the Default method in Java 8. (see example)
  • Java 8 Comparator Example (see here)
  • How to convert List to Map in Java 8 (solution)
  • How to join String in Java 8 (example)
  • Difference between abstract class and interface in Java 8? (answer)
  • 10 Free Courses for Experienced Java Programmers (courses)
  • How to use peek() method in Java 8 (example)
  • How to sort the may by values in Java 8? (example)
  • How to format/parse the date with LocalDateTime in Java 8? (tutorial)
  • 5 Free Courses to learn Java 8 and 9 (courses)
Thanks for reading this article so far. If you like this tutorial then please share with your friends and colleagues. If you have any questions or feedback then please drop a note.

P.S.: If you want to learn more about new features in Java 8 then please see the tutorial What's New in Java 8. It explains all the important features of Java 8 e.g. lambda expressions, streams, functional interface, Optional, new Date Time API and other miscellaneous changes.

5 comments:

  1. Nice article with good example

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

    ReplyDelete
  3. This is great article to start but there is a issue in transform method .collect(toList()) its ask to implement toList() method, we need to write .collect(Collectors.toList());

    ReplyDelete
    Replies
    1. As static import allows you to write .collect(toList())

      import static java.util.stream.Collectors.toList;

      Delete
  4. I found this method in a spring example and I have no idea what's going on. So thanks to help us.

    ReplyDelete