All TalkersCode Topics

Follow TalkersCode On Social Media

devloprr.com - A Social Media Network for developers Join Now ➔

Java Streams Convert List To Map

Last Updated : Mar 11, 2024

Java Streams Convert List To Map

In this article we will show you the solution of java streams convert list to map, Java Streams offer a potent and succinct method for processing data collections in a functional programming manner.

Working with data frequently involves transforming a List into a Map based on predetermined criteria.

This work is made easier by the Collectors.groupingBy() method in Java Streams, which enables us to organise List element into a Map depending on a provided categorization function.

The key for each element in the resulting Map is determined by the classification function that is passed as an input to the Collectors.groupingBy() method.

After that, it compiles the List's components into a Map whose keys are chosen by the categorization algorithm.

For dealing with data that needs to be categorized or organized according to specific attributes, this method is quite helpful.

We could, for instance, arrange a list of objects according to their properties or a list of strings according to their lengths. Now we'll talk about the Java streams convert list to map concept.

Step By Step Guide On Java Streams Convert List To Map :-

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class ListToMapExample {
    public static void main(String[] args) {
        // Sample list of objects
        List<Person> personList = Arrays.asList(
                new Person("Aman", 25),
                new Person("Naman", 30),
                new Person("Gagan", 25),
                new Person("Chagan", 35),
                new Person("Magan", 30)
        );
        // Convert list to map using Collectors.groupingBy() method
        Map<Integer, List<Person>> ageGroupMap = personList.stream()
                .collect(Collectors.groupingBy(Person::getAge));
        // Print the resulting map
        ageGroupMap.forEach((age, persons) -> {
            System.out.println("Age: " + age);
            System.out.println("Persons: " + persons);
            System.out.println();
        });
    }
    static class Person {
        private String name;
        private int age;
        public Person(String name, int age) {
            this.name = name;
            this.age = age;
        }
        public String getName() {
            return name;
        }
        public int getAge() {
            return age;
        }
        @Override
        public String toString() {
            return "Person{" +
                    "name='" + name + '\'' +
                    ", age=" + age +
                    '}';
        }
    }
}
  1. You can see that we wrote the Java code to transform the list to the map here.
  2. We have a Person class at the beginning of the code that represents people with names and ages.
  3. Several Person objects with various names and ages can be found in the list personList.
  4. Using the Collectors.groupingBy() method, we can turn this list into a map with lists of people in each age group as the values and ages as the keys.
  5. We may quickly conduct actions on the list's elements by using this method when it is invoked on the personList stream.
  6. The groupingBy() process takes a classification function, Person::getAge, which extracts the age of each person, groups the people based upon their ages, creating a map where the keys are the ages as well as the values are lists of people with the same age.
  7. After the conversion is completed, we continue over the resulting ageGroupMap with the forEach() method.
  8. For every entry in the map, we print the age and the corresponding list of people.

Conclusion :-

As a result, we were able to understand how Java streams transform list to map.

Additionally, we discovered how to use Java Streams and Collectors.A quick and effective way to turn a List into a Map depending on certain criteria is to use the groupingBy() method.

I hope this article on java streams convert list to map helps you and the steps and method mentioned above are easy to follow and implement.

Author Image About Anjali

Experienced Computer Programmer with a broad range of experience in technology. Strengths in application development and Object Oriented architecture design, front end programming, usability and multimedia technology. Expert in coding languages such as C, C++ Java, JavaScript, PHP and more.

Follow Anjali On Linkedin 🡪