Wednesday, 11 January 2017

Map operation in Java Stream API

Map operations, 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 here is; since new stream is returned map operation is an intermediate operation.

map method

Java stream API provides a 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.

Mapping examples in Java Stream

  1. 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]
    
  2. 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
    
  3. There is an employee class and you want the name of all the female employees.
    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 os 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.

Code examples

  1. If you want to get the total of salaries for the employees (Using the employee class as above) -
    int totalSalary = empList.stream().mapToInt(e -> e.getSalary()).sum();
    System.out.println("total of salaries " + totalSalary);
    

    Output

    total of salaries 31000
    
  2. If you want 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
    
  3. 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!


Related Topics

  1. Stream API in Java 8
  2. Parallel Stream in Java Stream API
  3. Java Stream API Examples
  4. Reduction Operations in Java Stream API
  5. Lambda expressions in Java 8

You may also like -

>>>Go to Java advance topics page

3 comments:

  1. your information is really awesome as well as it is very excellent and i got more interesting information from your blog.
    PHP Training in Chennai

    ReplyDelete
  2. You have provided an nice article, Thank you very much for this one. And i hope this will be useful for many people.. and i am waiting for your next post keep on updating these kinds of knowledgeable things...

    Android App Development Company

    ReplyDelete
  3. great and nice blog thanks sharing..I just want to say that all the information you have given here is awesome...Thank you very much for this one.
    web design Company
    web development Company
    web design Company in chennai
    web development Company in chennai
    web design Company in India
    web development Company in India

    ReplyDelete