First Steps in Java 8 Streams: map and collect.

Datetime:2016-08-23 00:36:31         Topic: Java8          Share        Original >>
Here to See The Original Article!!!

The Streams API in Java 8 is a big change in how to use collections of objects in Java. The for-loops typically used through code is now replaced with various new patterns for iteration, transformation / mapping and filtering collections.

In this tutorial I will demonstrate taking a collection of Customer objects and from it creating a new collection, just containing their ids. I then output this to show what it contains.

Here’s the code:

package tutorials;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Tutorial1 {

	public static void main(final String[] args) {
		// Create a list.
		final List<Customer> customers = Arrays.asList(
				new Customer(1001l, "Alpha Ltd"), 
				new Customer(1002l, "Bravo Ltd"),
				new Customer(1003l, "Charlie Ltd")
		// Turn into a list of Ids.
		final List<Long> ids = customers.stream()
		System.out.println("Ids = " + ids);

class Customer {
	private final Long id;
	private final String name;
	Customer(Long id, String name) {
		this.id = id;
		this.name = name;
	Long getId() {
		return id;
	String getName() {
		return name;

It is how we generate the second collection that is important. Here I’ll break it down:

We always use this stream method to go from a Collection object to a Stream object:


Once we have a Stream we call map – this is because instead of a Collection of Customer objects we want a Collection of Longs. We need a way to convert each Customer to a Long and the Customer.getId() method provides this – note the ‘::’ syntax.


this is equivalent to

    .map(customer -> customer.getId())

Now we are working with a Stream from which we would like a List. The ‘collect’ method allows us to go from the more work-in-progress Stream to our desired Collection:


The output from running this is:

Ids = [1001, 1002, 1003]

But what about the Scala version?

After writing the above I edited it to be normal Scala and this is what I came up with. Sadly it’s a lot shorter and shows how much more verbose Java is:

package tutorials

import java.util.stream.Collectors

object Tutorial1 extends App {
		// Create a list.
		val customers = List(Customer(1001l, "Alpha Ltd"),
		                    Customer(1002l, "Bravo Ltd"),
				                Customer(1003l, "Charlie Ltd"));
		// Turn into a list of Ids.
		val ids = customers.map { _.id }
		println(s"Ids = $ids")

case class Customer(id:Long, name:String)

The output:

Ids = List(1001, 1002, 1003)