map method of Stream class

  • Java 8 Stream’s map method is intermediate operation and consumes single element forom input Stream and produces single element to output Stream.
  • It simply used to convert Stream of one type to another.
  •  signature of Stream’s map method.
    • <R> Stream<R> map(Function<? super T,? extends R>mapper)
  • Types of map method in Stream class
    • map()
    • mapToInt()
    • mapToLong()
    • mapToDouble()
Stream map

Another Example :

package com.demo.java8;

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

public class Demo3 {
	public static void main(String[] args) {
		List<Emp> empList = Arrays.asList(new Emp[] { 
				new Emp("1","Mumbai","20"),
				new Emp("2","Delhi","23"),
				new Emp("3","Kolkata","25"),
				new Emp("4","Chennai","18"),
				new Emp("5","Mumbai","11"),
				new Emp("6","Kolkata","30"),
				new Emp("7","Chennai","35"),
				new Emp("8","Mumbai","15"),
				new Emp("9","Delhi","22"),
				new Emp("10","Kolkata","27")
				});
		
		List<String> empIdList = empList.stream().map(x->x.getId()).collect(Collectors.toList());
		empList.stream().map(x->x.getId()).forEach(System.out::println);
	}
}
class Emp3{
	private String id;
	private String city;
	private String age;
	public Emp3(String id, String city, String age) {
		super();
		this.id = id;
		this.city = city;
		this.age = age;
	}
	public String getId() {return id;}
	public String getCity() {return city;}
	public String getAge() {return age;}
	@Override
	public String toString() {
		return "Emp [id=" + id + ", city=" + city + ", age=" + age + "]";
	}
}

Leave a Comment