flatMap method of Stream class

  • In Java 8, we can use the flatMap to convert the above 2 levels Stream into one Stream level or a 2d array into a 1d array.
# Stream<String[]>
# Stream<Stream<String>>
# String[][]

[
  [1, 2],
  [3, 4],
  [5, 6]
]

Convert to

# Stream<String>
# String[]

[1, 2, 3, 4, 5, 6]

Example :

package com.demo.java8;

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

public class Demo4 {
	public static void main(String[] args) {
		List<Emp4> mumbaiList  = Arrays.asList(new Emp4[] { 
				new Emp4("1","Mumbai","20"),new Emp4("5","Mumbai","11"),new Emp4("8","Mumbai","15")			
				});
		List<Emp4> delhiList  = Arrays.asList(new Emp4[] { 
				new Emp4("2","Delhi","23"),	new Emp4("9","Delhi","22")	});
		
		List<Emp4> kokataList  = Arrays.asList(new Emp4[] { 
				new Emp4("3","Kolkata","25"),new Emp4("6","Kolkata","30"),new Emp4("10","Kolkata","27"),	
				});
		
		List<Emp4> chennaiList  = Arrays.asList(new Emp4[] { 
				new Emp4("4","Chennai","18"),new Emp4("7","Chennai","35"),		
				});
		
		List<List<Emp4>> masterList = new ArrayList<>();
		
		masterList.add(mumbaiList);
		masterList.add(delhiList);
		masterList.add(kokataList);
		masterList.add(chennaiList);
		
		//Example : With list of list
		List<String> empIdList = masterList.stream().flatMap(x->x.stream()).map(x->x.getId()).collect(Collectors.toList());
		masterList.stream().flatMap(x->x.stream()).map(x->x.getId()).forEach(System.out::println);
//		masterList.parallelStream().flatMap(x->x.parallelStream()).map(x->x.getId()).forEach(System.out::println);
		
		String[][] array = new String[][]{{"a", "b"}, {"c", "d"}, {"e", "f"}};
		
		///Exmaple : With multidimentional array
		List<String> idList = Arrays.stream(array).flatMap(x->Arrays.stream(x)).collect(Collectors.toList());
		
		Arrays.stream(array).flatMap(x->Arrays.stream(x)).forEach(System.out::println);
	}
}

class Emp4{
	private String id;
	private String city;
	private String age;
	public Emp4(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 + "]";
	}
}

Reference :

Leave a Comment