How to use Java 8 Stream Map Examples with a List or Array

how-to-use-java-8-stream-map-examples-feature-image

[no_toc]
Converting or transforming a List and Array Objects in Java is a common task when programming. In the tutorial, We show how to do the task with lots of Java examples code by 2 approaches:

  • Using Traditional Solution with basic Looping
  • Using a powerful API – Java 8 Stream Map

Now let’s do details with examples!

Related posts:
Java 8
Java 8 Streams

Java Transform a List with Traditional Solution by Looping Examples

Before Java 8, for mapping a List Objects, we use the basic approach with looping technical solution.

Looping Example – Java Transform an Integer List

– Example: How to double value for each element in a List?

package com.ozenero.stream;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class StreamMapExamples {
	public static void main(String[] args) {
		List intLst = Arrays.asList(1, 2, 3, 4);
		
		// How to double value for each element in a List
		// n -> n*2
		
		List newLst = new ArrayList();
		
		for(int i : intLst) {
			newLst.add(i*2);
		}
		
		System.out.println(newLst);
		// [2, 4, 6, 8]
	}
}

Looping Example – Java Transform a String List

– Example: How to uppercase string value for each element in a String List?

package com.ozenero.stream;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class StreamMapExamples {
	public static void main(String[] args) {
		List strLst = Arrays.asList("one", "two", "three", "four");
		
		// How to upper-case for each element in a List
		// one -> ONE
		
		List newLst = new ArrayList();
		
		for(String str : strLst) {
			newLst.add(str.toUpperCase());
		}
		
		System.out.println(newLst);
		// [ONE, TWO, THREE, FOUR]
	}
}

Looping Example – Transform a Custom Object List

Create a Customer class:

class Customer{
	
	private String firstname;
	private String lastname;
	
	public String getFirstname() {
		return firstname;
	}
	
	public String getLastname() {
		return lastname;
	}
	
	Customer(String firstname, String lastname){
		this.firstname = firstname;
		this.lastname = lastname;
	}
}

– Example: How to get a string list of fullname of Customer List?

List custList = Arrays.asList(
							new Customer("Jack", "Smith"),
							new Customer("Joe", "Johnson"),
							new Customer("Richard", "Brown"),
							new Customer("Thomas", "Wilson")
						);

List fullnameList = new ArrayList();

for(Customer c: custList) {
	String fullname = c.getFirstname() + " " + c.getLastname(); 
	fullnameList.add(fullname);
}

System.out.println(fullnameList);
// [Jack Smith, Joe Johnson, Richard Brown, Thomas Wilson]

Java 8 Stream Map Examples to Convert or Transform a List

With Java 8, We have a powerful Stream API map() method that help us transform or convert each element of stream with more readable code:

 Stream map(Function mapper);

-> It returns a stream consisting of the results of applying the given function to the elements of this stream.

Now we can convert or transform a List with following way:

List -> Stream -> map() -> Stream -> List

Stream Map Example with Integer List

– Example: Transform a Java number list to a double value number list by using stream map.

Integer List -> Stream -> map() -> Stream -> Another Integer List

– Code:

package com.ozenero.stream;

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

public class StreamMapExamples {
	public static void main(String[] args) {
		List intLst = Arrays.asList(1, 2, 3, 4);
		
		// How to double value for each element in a List
		// n -> n*2
		//  we use map function of stream:
		// 	List -> Stream -> map() -> Stream -> List
		
		List newLst = intLst.stream()
										.map(n->n*2)
											.collect(Collectors.toList());
		
		System.out.println(newLst);
		// [2, 4, 6, 8]
	}
}

In above code, we use collect() method to transform stream elements into another container such as a List.

Stream Map Example with String List

– Example: Convert a Java string list to an uppercase string list by Stream Map.

String List -> Stream -> map() -> Stream -> Uppercase String List

– Code:

List strLst = Arrays.asList("one", "two", "three", "four");

// How to upper-case for each element in a List
// We use map() method of Stream
// List -> Stream -> map() -> Stream -> List

List newLst = strLst.stream()
								.map(str->str.toUpperCase())
									.collect(Collectors.toList());

System.out.println(newLst);
// [ONE, TWO, THREE, FOUR]

Stream Map Example with Custom Object List

– Example: Transform an Java object list to another string list.

Customer List -> Stream -> map() -> Stream -> String List

– Code:

List custList = Arrays.asList(
		new Customer("Jack", "Smith"),
		new Customer("Joe", "Johnson"),
		new Customer("Richard", "Brown"),
		new Customer("Thomas", "Wilson")
	);

List fullnameList = custList.stream()
			.map(c -> c.getFirstname() + " " + c.getLastname())
				.collect(Collectors.toList());

System.out.println(fullnameList);
// [Jack Smith, Joe Johnson, Richard Brown, Thomas Wilson]

Parallel & Sequential Stream Map Examples

Stream provides a parallel API processing parallel(), so We can combine it with map() method to leverage the multiple cores on your computer for performance processing data.

List custList = Arrays.asList(
		new Customer("Jack", "Smith"),
		new Customer("Joe", "Johnson"),
		new Customer("Richard", "Brown"),
		new Customer("Thomas", "Wilson")
	);

custList.stream()
			.parallel()
			.map(c -> c.getFirstname() + " " + c.getLastname()) //concurrently mapping
				.forEach(System.out::println); //concurrently System.out:println
/*
	Richard Brown
	Thomas Wilson
	Joe Johnson
	Jack Smith
 */

– In above code, we use forEach() method to perform an action System.out::println for each stream element.

To switch from concurrently to sequential processing, We can use the sequential() API of Stream:

List custList = Arrays.asList(
		new Customer("Jack", "Smith"),
		new Customer("Joe", "Johnson"),
		new Customer("Richard", "Brown"),
		new Customer("Thomas", "Wilson")
	);

custList.stream()
			.parallel()
			.map(c -> c.getFirstname() + " " + c.getLastname())
			.sequential()
				.forEach(System.out::println);
/*
	Jack Smith
	Joe Johnson
	Richard Brown
	Thomas Wilson

 */

There are a difference order of items in the output between concurrently processing and sequential processing with forEach() method: result of the sequential processing remains the same order of original list while the parallel processing does NOT.

Java 8 Stream Map combines with Filter and Reduce

Java Stream Map with Filter

We can combines Stream Map with Filter mechanics.

Example:

Integer List -> Stream -> Filter odd number -> Map: double value of filtered (odd) number -> Stream -> Integer List

– Code:

List intLst = Arrays.asList(1, 2, 3, 4, 5, 6, 7);

// 
// n -> n*2

List newLst = intLst.stream()
								.parallel()
								.filter(i -> i%2 == 1)
								.map(i->{
									System.out.println(i);
									return i*2;	
								})
								.collect(Collectors.toList());

System.out.println(newLst);

/*
	5
	3
	7
	1
	[2, 6, 10, 14]
 */

See more about Stream Filter at post: link

Java Stream Map with Reduce

Question: How to sum all number of the final stream after mapping?
We can do the calculation by using reduce() function of Java Stream:

Stream.reduce(Integer identity, BinaryOperator accumulator)

– Code:

List intLst = Arrays.asList(1, 2, 3, 4, 5, 6, 7);

// How to double value for each element in a List
// n -> n*2

Integer total = intLst.stream()
								.parallel()
								.filter(i -> i%2 == 1)
								.map(i->{
									System.out.println(i);
									return i*2;	
								})
								.reduce(0, (i1, i2) -> i1 + i2);

System.out.println("Total: " + total);

/*
	5
	1
	3
	7
	Total: 32
 */

32 is a result of reduce funtion by sum all all numbers in final stream after mapping: (5*2 + 1*2 + 3*2 + 7*2).

Java 8 Stream Map Examples with Array

To apply Stream Map in Array with Java 8, We do 2 steps:

  • Create Stream from Array Objects.
  • Apply Stream Mapping for Array Objects as the same way we had done with above List Objects.

Example Code:

Customer[] customers = new Customer[] {
		new Customer("Jack", "Smith"),
		new Customer("Joe", "Johnson"),
		new Customer("Richard", "Brown"),
		new Customer("Thomas", "Wilson")
};

Arrays.stream(customers)
			.parallel()
			.map(c -> c.getFirstname() + " " + c.getLastname())
			.sequential()
				.forEach(System.out::println);
/*
	Jack Smith
	Joe Johnson
	Richard Brown
	Thomas Wilson

 */

Conclusion

We had done how to use Java 8 Stream Map with Examples:

  • How to transform Java Array or List with basic looping
  • Apply Java 8 Stream Map to Integer, String, Custom Object List
  • Combine map() method with filter() and reduce() functions of Java 8 Stream<>
  • Apply Stream Map to Java Array
  • Explore how to use parallel & sequential streams with map() method

Thanks for reading! See you later!

0 0 votes
Article Rating
Subscribe
Notify of
guest
900 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments