Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to convert List<AnyClassObject> to List<Map<String, String>> using Stream in java 8?

I have a List, I need to convert it to List<Map<String, String>>.

For e.g. consider below scenario:

public class AnyClass() {

    private String letter;

}

Now, suppose I have a list objectList which have multiple object with diff value of letter

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

List<AnyClass> objectList = new ArrayList();
objectList.add(new AnyClass("A"));
objectList.add(new AnyClass("B"));
objectList.add(new AnyClass("C"));
objectList.add(new AnyClass("D"));

now I want to convert it to List<Map<String, String>> using Stream in java 8.

I want to achieve the following:

List<Map<String, String>> listOfMaps = new ArrayList<>();

for(AnyClass object: objectList) {
    listOfMaps.add(ImmutableMap.<String, String>builder()
                    .put("ConstantKey","ConstantValue")
                    .put("ConstatKey2", object.getLetter())
                    .build());
}

>Solution :

It’s a simple map() and collect():

List<Map<String, String>> listOfMaps = objectList.stream()
        .map(o -> ImmutableMap.of(
                "ConstantKey", "ConstantValue",
                "ConstantKey2", o.getLetter()))
        .collect(Collectors.toList());

You might want to extract the map construction to a separate method to keep the lambda a little cleaner.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading