Monday, August 16, 2021

Java 8: Streams API: map vs flapMap

Both map & flatMap are used for transforming the stream data which produces another stream as method output. Map transforms one input to one output value whereas flatMap produces arbitrary (zero, one or more) number of values for each input. Syntax for both is as follows

<R> Stream<R> map(Function<? super T, ? extends R> mapper)

<R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper)

method returns a Stream

T is type of stream elements

R is element type of the new stream (note that, flatMap takes in Stream of type R)

mapper is stateless function that is applied to each element



       


package java8;
import java.util.*;

public class EmployeeDB {
	public static List<Employee> getEmployeeList(){
		List<Employee> empList = Arrays.asList(
				//int eId, String fName, String lName, double salary, List<Integer> phNumbers
				new Employee(5, "Sonu", "Panjabi", 1000, Arrays.asList(1234, 2345)),
				new Employee(7, "Ganu", "Marathi", 1500, Arrays.asList(3456, 4567)),
				new Employee(8, "Manu", "Bangali", 2000, Arrays.asList(5678, 6789)),
				new Employee(4, "Tonu", "Bihari", 3000, Arrays.asList(7890, 8901)),
				new Employee(1, "Kanu", "Asami", 3500, Arrays.asList(9012, 1230)),
				new Employee(6, "Ranu", "Kashmiri", 4000, Arrays.asList(9876, 8765)),
				new Employee(2, "Janu", "Kannadi", 4500, Arrays.asList(7654, 6543)),
				new Employee(3, "Monu", "Gujrathi", 5000, Arrays.asList(5432, 4321))
				);
		return empList;
	}
}
package java8.mapvsflatmap;

import java.util.stream.Collectors;
import java.util.stream.Stream;

import java8.EmployeeDB;

public class MapVsFlatMap {

	public static void main(String[] args) {
		System.out.println(EmployeeDB.getEmployeeList().stream().map(e-> e.getPhNumbers()).collect(Collectors.toList()));
		//<R> Stream<R> map(Function<? super T, ? extends R> mapper)
		//<List<Integer>> Stream<List<Integer>> java.util.stream.Stream.map(Function<? super Employee, ? extends List<Integer>> mapper)
		System.out.println(EmployeeDB.getEmployeeList().stream().flatMap(e -> e.getPhNumbers().stream()).collect(Collectors.toList()));
		//<R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper)
		//<Integer> Stream<Integer> java.util.stream.Stream.flatMap(Function<? super Employee, ? extends Stream<? extends Integer>> mapper)
		
		Stream.of("1", "2").mapToInt(s -> Integer.valueOf(s)).forEach(s -> System.out.print(", mapToInt: "+s));
		System.out.println();
		Stream.of("one", "two").flatMapToInt(s -> s.chars()).forEach(s -> System.out.print(", flatMapToInt: "+s));
		
		
	}

}

No comments:

SpringBoot: Features: SpringApplication

Below are a few SpringBoot features corresponding to SpringApplication StartUp Logging ·          To add additional logging during startup...