1. Introduction
A Multimap is a type of map in Java that can map a single key to multiple values. It’s not a part of the standard Java Collections Framework but is available through third-party libraries like Google’s Guava. Converting a List to a Multimap can be quite handy when we have a list of objects, and we want to group them by a specific property or field. In this example, we’ll be using Google Guava’s Multimap to achieve this.
2. Program Steps
1. Add the Guava library to your project.
2. Define a simple class to demonstrate the conversion.
3. Create and initialize a List with objects of the class.
4. Convert the List to a Multimap.
5. Display the contents of the Multimap.
3. Code Program
// Step 1: Add Guava library to your project.
// You can add it using build tools like Maven or Gradle.
// Here is a Maven dependency example:
// <dependency>
// <groupId>com.google.guava</groupId>
// <artifactId>guava</artifactId>
// <version>30.1-jre</version> <!-- Replace with the version you are using -->
// </dependency>
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
import java.util.Arrays;
import java.util.List;
// Step 2: Define a simple class to demonstrate the conversion
class Student {
String name;
String grade;
Student(String name, String grade) {
this.name = name;
this.grade = grade;
}
}
public class ListToMultimap {
public static void main(String[] args) {
// Step 3: Create and initialize a List with objects of the class
List<Student> studentList = Arrays.asList(
new Student("John", "A"),
new Student("Jane", "B"),
new Student("Mike", "A"),
new Student("Sara", "C"),
new Student("Paul", "B")
);
// Step 4: Convert the List to a Multimap
Multimap<String, Student> studentsMultimap = ArrayListMultimap.create();
for (Student student : studentList) {
studentsMultimap.put(student.grade, student);
}
// Step 5: Display the contents of the Multimap
System.out.println("Multimap: ");
studentsMultimap.asMap().forEach((grade, studentsInGrade) ->
System.out.println("Grade: " + grade + " - Students: " + studentsInGrade)
);
}
}
Output:
Multimap: Grade: A - Students: [John, Mike] Grade: B - Students: [Jane, Paul] Grade: C - Students: [Sara]
4. Step By Step Explanation
Step 1: Include the Google Guava library in your project using a build tool like Maven or Gradle.
Step 2: Define a simple Student class that has name and grade as attributes.
Step 3: Create and initialize a List of Student objects.
Step 4: Instantiate a Multimap and populate it by iterating through the list of students, using the grade as the key and the Student object as the value.
Step 5: Display the contents of the Multimap. Here, each grade is mapped to a list of Student objects associated with that grade.