Java 8 Stream map() Example





Hey guys in this post, we will discuss everything about map() in Streams which is introduced in Java 8.

Introduction


  • map() function returns a stream consisting of the results of applying the given function to the element of this function. map() function is in java.util.stream package
  • In other words, map() method is used to transform one object into another by applying a function
  • map() method takes a function as an argument Stream.map(function arg)
  • map() function provides intermediate operation. Intermediate operation are lazy operation. it does not apply until you apply terminal operations like forEach() or collect() methods.
  • map() invoked on a stream instance and after finish their processing they give stream instance as output

Examples


#1 Convert string of list to numbers

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

public class Test {
	public static void main(String[] args) {
		List<String> list = Arrays.asList("1", "2", "3", "4", "5");
		List<Integer> numbers = new ArrayList<>();
		
		//old way
		for (String str : list) {
			numbers.add(Integer.valueOf(str));
		}
		
		//new way
		numbers = list.stream().map(string -> Integer.valueOf(string)).collect(Collectors.toList());
		System.out.println(numbers);
	}
}
//[1,2,3,4,5]

#2 Convert list of string into uppercase and lowercase with map()

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

public class Example2 {
	
	public static void main(String[] args) {
		
		List<String> list = Arrays.asList("HP", "Lenovo", "Dell", "Macbook", "Acer");
		
		List<String> firstList = list.stream()
									.map(laptop -> laptop.toUpperCase())
									.collect(Collectors.toList());
		System.out.println(firstList);
		
		firstList.stream()
					.map(laptop -> laptop.toLowerCase())
					.forEach(System.out::println);
	}
}	

Further read on map() at https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#map-java.util.function.Function-




About the author

Bushan Sirgur

Well, I am Bushan Sirgur from Banglore, India. Currently, I am working as a Software Developer in a Service Base Company. I am interested in JAVA/J2EE, Angular 2, JavaScript, jQuery, MongoDB.

View all posts

Leave a Reply

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