Java 8 Streams map() examples

In Java 8, stream().map() lets you convert an object to something else. Review the following examples :

1. A List of Strings to Uppercase

1.1 Simple Java example to convert a list of Strings to upper case.

TestJava8.java

package com.mkyong.java8;

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

public class TestJava8 {

    public static void main(String[] args) {

        List<String> alpha = Arrays.asList("a", "b", "c", "d");

        //Before Java8
        List<String> alphaUpper = new ArrayList<>();
        for (String s : alpha) {
            alphaUpper.add(s.toUpperCase());
        }

        System.out.println(alpha); //[a, b, c, d]
        System.out.println(alphaUpper); //[A, B, C, D]

        // Java 8
        List<String> collect = alpha.stream().map(String::toUpperCase).collect(Collectors.toList());
        System.out.println(collect); //[A, B, C, D]

        // Extra, streams apply to any data type.
        List<Integer> num = Arrays.asList(1,2,3,4,5);
        List<Integer> collect1 = num.stream().map(n -> n * 2).collect(Collectors.toList());
        System.out.println(collect1); //[2, 4, 6, 8, 10]

    }

}

2. List of objects -> List of String

2.1 Get all the name values from a list of the staff objects.

Staff.java

package com.mkyong.java8;

import java.math.BigDecimal;

public class Staff {

    private String name;
    private int age;
    private BigDecimal salary;
	//...
}
TestJava8.java

package com.mkyong.java8;

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

public class TestJava8 {

    public static void main(String[] args) {

        List<Staff> staff = Arrays.asList(
                new Staff("mkyong", 30, new BigDecimal(10000)),
                new Staff("jack", 27, new BigDecimal(20000)),
                new Staff("lawrence", 33, new BigDecimal(30000))
        );

        //Before Java 8
        List<String> result = new ArrayList<>();
        for (Staff x : staff) {
            result.add(x.getName());
        }
        System.out.println(result); //[mkyong, jack, lawrence]

        //Java 8
        List<String> collect = staff.stream().map(x -> x.getName()).collect(Collectors.toList());
        System.out.println(collect); //[mkyong, jack, lawrence]

    }

}

3. List of objects -> List of other objects

3.1 This example shows you how to convert a list of staff objects into a list of StaffPublic objects.

Staff.java

package com.mkyong.java8;

import java.math.BigDecimal;

public class Staff {

    private String name;
    private int age;
    private BigDecimal salary;
	//...
}

StaffPublic.java

package com.mkyong.java8;

public class StaffPublic {

    private String name;
    private int age;
    private String extra;
    //...
}


3.2 Before Java 8.

BeforeJava8.java

package com.mkyong.java8;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class BeforeJava8 {

    public static void main(String[] args) {

        List<Staff> staff = Arrays.asList(
                new Staff("mkyong", 30, new BigDecimal(10000)),
                new Staff("jack", 27, new BigDecimal(20000)),
                new Staff("lawrence", 33, new BigDecimal(30000))
        );

        List<StaffPublic> result = convertToStaffPublic(staff);
        System.out.println(result);

    }

    private static List<StaffPublic> convertToStaffPublic(List<Staff> staff) {

        List<StaffPublic> result = new ArrayList<>();

        for (Staff temp : staff) {

            StaffPublic obj = new StaffPublic();
            obj.setName(temp.getName());
            obj.setAge(temp.getAge());
            if ("mkyong".equals(temp.getName())) {
                obj.setExtra("this field is for mkyong only!");
            }

            result.add(obj);
        }

        return result;

    }

}

Output


[
	StaffPublic{name='mkyong', age=30, extra='this field is for mkyong only!'}, 
	StaffPublic{name='jack', age=27, extra='null'}, 
	StaffPublic{name='lawrence', age=33, extra='null'}
]

3.3 Java 8 example.

NowJava8.java

package com.mkyong.java8;

package com.hostingcompass.web.java8;

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

public class NowJava8 {

    public static void main(String[] args) {

        List<Staff> staff = Arrays.asList(
                new Staff("mkyong", 30, new BigDecimal(10000)),
                new Staff("jack", 27, new BigDecimal(20000)),
                new Staff("lawrence", 33, new BigDecimal(30000))
        );

		// convert inside the map() method directly.
        List<StaffPublic> result = staff.stream().map(temp -> {
            StaffPublic obj = new StaffPublic();
            obj.setName(temp.getName());
            obj.setAge(temp.getAge());
            if ("mkyong".equals(temp.getName())) {
                obj.setExtra("this field is for mkyong only!");
            }
            return obj;
        }).collect(Collectors.toList());

        System.out.println(result);

    }
	
}

Output


[
	StaffPublic{name='mkyong', age=30, extra='this field is for mkyong only!'}, 
	StaffPublic{name='jack', age=27, extra='null'}, 
	StaffPublic{name='lawrence', age=33, extra='null'}
]

References

  1. Processing Data with Java SE 8 Streams, Part 1
  2. Java 8 – Filter a Map examples
  3. Java 8 flatMap example
  4. Collectors JavaDoc

18 comments on “Java 8 Streams map() examples

  1. maybe its just me,

    But I cant find on entire internet an easy way to implement a search through a Map, to find one ‘key'(String for example) and then print it out with streams/Lambda….

    wondering if you can help?

    Reply
  2. Hi MKyong,

    maybe you could help me.
    I have to convert an Entity into a DTO.

    In my Reader module, I have a method that fetches data from a DB and inserts it into our local DB.

    I have to get this referente (of the inserted data) in the ‘processor’ module.
    Actually I couldnt do it so maybe I could use map to convert it and get this updated table records in order to publish them in a rabbit queue, but I don´t know how to do it.

    Reply
  3. hi , i am trying copy list elements from list<A> to LIst<B> and facing some type error :

    my code is :

       List<AttachmentTypeDto> attachmentTypeList=clientDetails.getAttachmentTypeDto();
             List<ClientAttachmentTypeEntity> mappedAttachmentList=attachmentTypeList.stream().map(temp ->{
                ClientAttachmentTypeEntity toAttachmentObject=new ClientAttachmentTypeEntity();
                toAttachmentObject.setAttachmentTypeId(temp.getAttachmentTypeId());
                toAttachmentObject.setClientId(temp.getClientId());

             }).collect(Collectors.toList());

    it gives me error like this :

    The method map(Function<? super AttachmentTypeDto,? extends R>) in the type Stream<AttachmentTypeDto> is not applicable for the arguments ((<no type> temp) -> {})

    Reply
    1. you may please add return toAttachmentObject before closing the block under map

      Reply
  4. Does new object Creation affects performance???
    // convert inside the map() method directly.
    List result = staff.stream().map(temp -> {
    StaffPublic obj = new StaffPublic();
    obj.setName(temp.getName());
    obj.setAge(temp.getAge());
    if (“mkyong”.equals(temp.getName())) {
    obj.setExtra(“this field is for mkyong only!”);
    }
    return obj;

    }).collect(Collectors.toList());

    Reply
  5. public class ExerciseMapExample2 {

    public static void main(String ...args) {

    List<Staff> staff = Arrays.asList(
    new Staff("mkyong", 30, new BigDecimal(10000)),
    new Staff("jack", 27, new BigDecimal(20000)),
    new Staff("lawrence", 33, new BigDecimal(30000))
    );

    // convert inside the map() method directly.
    List<StaffPublic> result = staff.stream().map(ExerciseMapExample2::process).collect(Collectors.toList());

    System.out.println(result);

    }

    private static StaffPublic process(Staff temp) {
    StaffPublic obj = new StaffPublic();
    obj.setName(temp.getName());
    obj.setAge(temp.getAge());
    if ("mkyong".equals(temp.getName())) {
    obj.setExtra("this field is for mkyong only!");
    }
    return obj;
    }
    }

    Reply
  6. 3.3 Java 8 example. ,
    NowJava8 Class.

    // convert inside the map() method directly.
    List result = staff.stream().map(temp -> {
    StaffPublic obj = new StaffPublic();
    obj.setName(temp.getName());
    obj.setAge(temp.getAge());
    if (“mkyong”.equals(temp.getName())) {
    obj.setExtra(“this field is for mkyong only!”);
    }
    return obj;
    }).collect(Collectors.toList());

    System.out.println(result);
    the above function will nowhere return the output you have specified. It will only something like the below.
    com.sample.process.StaffPublic@3b07d329, com.sample.process.StaffPublic@41629346, com.sample.process.StaffPublic@404b9385

    Please putt correct code and respective output for the same.

    Reply
    1. Hi Vankatesh,

      Please override toString() method in “StaffPublic” class then you will get correct output.

      code is perfect, such a nice blog, Thanks MKYong.

      Reply
  7. Wouldn’t this bit create a new instance of StaffPublic for each element in the List?:

    .map(temp -> {
    StaffPublic obj = new StaffPublic();
    obj.setName(temp.getName());
    obj.setAge(temp.getAge());
    if (“mkyong”.equals(temp.getName())) {
    obj.setExtra(“this field is for mkyong only!”);
    }
    return obj;
    }

    Reply
  8. Instead of map(x -> x.getName()) can be used map(Staff::getName).

    Reply

Leave a Comment

Your email address will not be published. Required fields are marked *