Java 8 Convert List to Map

By Yashwant Chavan, Views 64029, Date 06-Nov-2016

In this tutorial you will learn about how to convert List to Map using Java 8 Collectors.toMap() api.

tags java

Refer below steps.

  • Create Person Pojo along with different attributes.
  • Add some elements into a List.
  • Convert List of Objects to Stream of Objects using java.util.Collection.stream() method.
  • Performs a reduction operation on the elements of the stream using a Collector (Stream.collect()).
  • Define Collector using ( Collectors.toMap(p -> p.getPersonId(), p -> p.getName()) ) method, Refer Example # 1.
  • Define keyMapper( p -> p.getPersonId() ) and valueMapper( p -> p.getName() ) functions to collect data into resultant Map with the help of Collectors.toMap() method.
  • Print resultant Map.

Person Pojo

Create simple Person pojo class with different attributes such as personId, gender, name, age and gender.

package com.technicalkeeda.app;
public class Person {
    private int personId;
    private String name;
    private int age;
    private Gender gender;

    public Person(int personId, String name, int age, Gender gender) {
        super();
        this.personId = personId;
        this.name = name;
        this.age = age;
        this.gender = gender;
    }

    public boolean isMale() {
        return this.gender == Gender.MALE;
    }

    public boolean isFemale() {
        return this.gender == Gender.FEMALE;
    }

    public int getPersonId() {
        return personId;
    }

    public void setPersonId(int personId) {
        this.personId = personId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Gender getGender() {
        return gender;
    }

    public void setGender(Gender gender) {
        this.gender = gender;
    }

    @Override
    public String toString() {
        StringBuilder str = null;
        str = new StringBuilder();
        str.append("Person Id:- " + getPersonId() + " Gender:- " + getGender() + " Name:- " + getName() + " Age:- " +
            getAge());
        return str.toString();
    }

    public static enum Gender {
        MALE,
        FEMALE
    }

}

Example 1

In this example we will convert List<Person> to Map<Integer, String>

package com.technicalkeeda.app;

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

import com.technicalkeeda.app.Person.Gender;

public class Java8StreamListToMap {
    public static void main(String[] args) {
        List <Person> persons = new ArrayList <Person> ();
        persons.add(new Person(1, "Divya", 24, Gender.FEMALE));
        persons.add(new Person(2, "Mahesh", 22, Gender.MALE));
        persons.add(new Person(3, "Dinesh", 32, Gender.MALE));

        Map <Integer, String> map = persons.stream().collect(Collectors.toMap(p -> p.getPersonId(), p -> p.getName()));
        System.out.println("Map:- " + map);

    }
}

output

Map:- {1=Divya, 2=Mahesh, 3=Dinesh}

Example 2

In this example we will convert List<Person> to Map<Integer, Person>

package com.technicalkeeda.app;

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

import com.technicalkeeda.app.Person.Gender;

public class Java8StreamListToMap {
    public static void main(String[] args) {
        List <Person> persons = new ArrayList <Person> ();
        persons.add(new Person(1, "Divya", 24, Gender.FEMALE));
        persons.add(new Person(2, "Mahesh", 22, Gender.MALE));
        persons.add(new Person(3, "Dinesh", 32, Gender.MALE));

        Map <Integer, Person> map = persons.stream().collect(Collectors.toMap(p -> p.getPersonId(), p -> p));

        System.out.println("Map:- " + map);

    }
}

output

Map:- {1=Person Id:- 1 Gender:- FEMALE Name:- Divya Age:- 24, 2=Person Id:- 2 Gender:- MALE Name:- Mahesh Age:- 22, 3=Person Id:- 3 Gender:- MALE Name:- Dinesh Age:- 32}

Example 3

In this example you will get Duplicate key Exception if you try to process duplicate while converting to Map.

package com.technicalkeeda.app;

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

import com.technicalkeeda.app.Person.Gender;

public class Java8StreamListToMap {
    public static void main(String[] args) {
        List <Person> persons = new ArrayList < Person > ();
        persons.add(new Person(1, "Divya", 24, Gender.FEMALE));
        persons.add(new Person(2, "Mahesh", 22, Gender.MALE));
        persons.add(new Person(3, "Dinesh", 32, Gender.MALE));
        persons.add(new Person(3, "Yashwant", 30, Gender.MALE));

        Map <Integer, Person> map = persons.stream().collect(Collectors.toMap(p -> p.getPersonId(), p -> p));

        System.out.println("Map:- " + map);

    }
}

output

Exception in thread "main" java.lang.IllegalStateException: Duplicate key Person Id:- 3 Gender:- MALE Name:- Dinesh Age:- 32
 at java.util.stream.Collectors.lambda$throwingMerger$0(Collectors.java:133)
 at java.util.HashMap.merge(HashMap.java:1253)
 at java.util.stream.Collectors.lambda$toMap$58(Collectors.java:1320)
 at java.util.stream.ReduceOps$3ReducingSink.accept(ReduceOps.java:169)
 at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1374)
 at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
 at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
 at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708)
 at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
 at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499)
 at com.technicalkeeda.app.Java8StreamListToMap.main(Java8StreamListToMap.java:18)
Yashwant Chavan

Yashwant Chavan

Hi there! I am founder of technicalkeeda.com and programming enthusiast. My skills includes Java,J2EE, Spring Framework, Nodejs, PHP and lot more. If you have any idea that you would want me to develop? Lets connect: yashwantchavan@gmail.com