Streams – map() operation

Stream map() in Java is an intermediate operation that converts/transforms one object into another. It is used to apply one given function to the elements of a Stream.

Stream map() takes a function as an argument, and it does not modify the original source of a stream. It just returns a new stream after applying the given function to all elements.

Stream map() operation – examples

Example 1:

Converting String elements from the List to the upper case.

class Test {

  public static void main(String[] args) {
    List<String> cities = new ArrayList<>(Arrays.asList("New York", "Paris", "London", "Monte Carlo", "Berlin"));

    cities.stream()
            .map(city -> city.toUpperCase())
            .forEach(city -> System.out.println(city));
  }
}

Output: NEW YORK PARIS LONDON MONTE CARLO BERLIN

This also can be written using method references:

class Test {

  public static void main(String[] args) {
    List<String> cities = new ArrayList<>(Arrays.asList("New York", "Paris", "London", "Monte Carlo", "Berlin"));

    cities.stream()
            .map(String::toUpperCase)
            .forEach(System.out::println);
  }
}

Output: NEW YORK PARIS LONDON MONTE CARLO BERLIN

You see how we converted the input Strings to the upper case with the map() method.

Example 2:

Using the map() method with custom objects. Let’s create a User class:

class User {
  private String name;
  private String username;
  private String membershipType;
  private String address;

  public User(String name, String username, String membershipType, String address) {
    this.name = name;
    this.username = username;
    this.membershipType = membershipType;
    this.address = address;
  }

  public String getName() {
    return name;
  }
}

Now let’s write the program that will create a stream from the list of users and transform the elements:

class Test {

  public static void main(String[] args) {
    List<User> users = getAllUsers();

    users.stream()
            .map(User::getName)
            .forEach(System.out::println);
  }
}

Output: John Megan Steve Melissa

Here, the map() method accepts the user object, and as a result, it returns a stream of users names, and that stream is passed to the forEach() method. So it takes a stream of one type and returns a new stream of another type.

I hope this tutorial was helpful to you. To learn more, check out other Java Functional Programming tutorials.

Leave a Reply

Your email address will not be published. Required fields are marked *