Map operations in Java Stream API, as the name suggests, are used to do the element mapping from one stream to another. Map operation will return a stream consisting of the results of applying the given function to the elements of this stream. So, whatever function is provided is applied on all the elements of the stream.
One thing to note here is; since new stream is returned map operation is an intermediate operation.
map method in Java Stream
Java stream API provides the following map method.
<R> Stream<R> map(Function<? super T,? extends R> mapper)- Returns a stream consisting of the results of applying the given function to the elements of this stream.
Here R is the element type of the new stream, T denotes the element type of the existing stream and mapper is the function which will be applied to all the elements of the stream.
Here note that mapper is an instance of Function which is a functional interface. Since it is a functional interface therefore it can be used as the assignment target for a lambda expression or method reference.
map() method examples in Java Stream
- You have a stream of some names and you want to get a list where names are stored in upper case. In that case using map()
method you can apply a function to all the elements of the stream to convert those elements to upper case and then using
collector, collect them in a list.
public class MappingDemo { public static void main(String[] args) { List<String> nameList = Stream.of("amy", "nick", "margo", "desi") .map(s->s.toUpperCase()) .collect(Collectors.toList()); System.out.println("Names in upper case" + nameList); } }
Output
Names in upper case[AMY, NICK, MARGO, DESI]
-
You have a list of salaries and you want to increase salaries by 10%.
List<Integer> myList = Arrays.asList(7000, 5000, 4000, 24000, 17000, 6000); myList.stream().map(i -> (i+ (i * 10/100))).forEach(System.out::println);
Output
7700 5500 4400 26400 18700 6600
-
There is an employee class and you want the name of all the female employees. In this example you can use filter() method to filter female employees and then using map() method you can get the name of those employees. Here using map() method you are transforming employee object to String object.
public class MappingDemo { public static void main(String[] args) { MappingDemo md = new MappingDemo(); List<Employee> empList = md.createList(); System.out.println("--- Name of female employees ---"); empList.stream() .filter(e -> (e.getSex() == 'F')) .map(e -> e.getName()) .forEach(System.out::println); } // Stub method to create list of employee objects private List<Employee> createList(){ List<Employee> empList = Arrays.asList(new Employee("E001", 40, "Ram", 'M', 5000), new Employee("E002", 35, "Sheila", 'F', 7000), new Employee("E003", 24, "Mukesh", 'M', 9000), new Employee("E004", 37, "Rani", 'F', 10000)); return empList; } class Employee { private String empId; private int age; private String name; private char sex; private int salary; Employee(String empId, int age, String name, char sex, int salary){ this.empId = empId; this.age = age; this.name = name; this.sex = sex; this.salary = salary; } public String getEmpId() { return empId; } public void setEmpId(String empId) { this.empId = empId; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public char getSex() { return sex; } public void setSex(char sex) { this.sex = sex; } public int getSalary() { return salary; } public void setSalary(int salary) { this.salary = salary; } } }
Output
--- Name of female employees --- Sheila Rani
Variants of map() method
There are three variants of map() method which return a primitive stream.
- mapToInt(ToIntFunction<? super T> mapper)- Returns an IntStream consisting of the results of applying the given function to the elements of this stream.
- mapToDouble(ToDoubleFunction<? super T> mapper)- Returns a DoubleStream consisting of the results of applying the given function to the elements of this stream.
- mapToLong(ToLongFunction<? super T> mapper)- Returns a LongStream consisting of the results of applying the given function to the elements of this stream.
Apart from that, in all the primitive type streams– IntStream, LongStream and Double Stream there is also a mapToObj() method.
For IntStream mapToObj() function is defined like this-
- mapToObj(IntFunction<? extends U> mapper)- Returns an object-valued Stream consisting of the results of applying the given function to the elements of this stream.
map() method with primitive streams examples
- If you want to get the total of salaries for the employees (Using the employee class as above), you can use mapToInt() method to
get an IntStream consisting of salaries and then apply sum() method on that int stream.
int totalSalary = empList.stream().mapToInt(e -> e.getSalary()).sum(); System.out.println("total of salaries " + totalSalary);
Output
total of salaries 31000
- If you want to get the maximum salary, you can use mapToInt() method to get an IntStream consisting of salaries and
then apply max() method on that int stream to get the maximum salary.
OptionalInt maxSalary = empList.stream().mapToInt(e -> e.getSalary()).max(); if(maxSalary.isPresent()){ System.out.println("Maximum Salary " + maxSalary.getAsInt()); }
Output
Maximum Salary 10000
-
For your testing you want to create 500 objects of some class -
List<Employee> empList = IntStream.rangeClosed(1, 500).mapToObj(Employee::new).collect(Collectors.toList());
That's all for this topic Map Operation in Java Stream API. If you have any doubt or any suggestions to make please drop a comment. Thanks!
>>>Return to Java Advanced Tutorial Page
Related Topics
You may also like-
No comments:
Post a Comment