1. Introduction
A Multimap is a special kind of Map in Java, which can map a single key to multiple values. It is part of third-party libraries like Google’s Guava. In this example, we will demonstrate how to convert a Set to a Multimap using Guava, which can be useful when you want to group the elements of a Set based on some properties.
2. Program Steps
1. Add the Guava library to your project.
2. Define a simple class to be stored in the Set.
3. Create and initialize a Set with objects of that class.
4. Convert the Set to a Multimap based on a property of the objects.
5. Print the Multimap to the console.
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.HashSet;
import java.util.Set;
// Step 2: Define a simple class to be stored in the Set
class Animal {
String name;
String type;
Animal(String name, String type) {
this.name = name;
this.type = type;
}
@Override
public String toString() {
return name;
}
}
public class SetToMultimap {
public static void main(String[] args) {
// Step 3: Create and initialize a Set with objects of that class
Set<Animal> animalSet = new HashSet<>(Set.of(
new Animal("Lion", "Mammal"),
new Animal("Tiger", "Mammal"),
new Animal("Snake", "Reptile"),
new Animal("Crocodile", "Reptile")
));
// Step 4: Convert the Set to a Multimap based on a property of the objects
Multimap<String, Animal> animalMultimap = ArrayListMultimap.create();
for (Animal animal : animalSet) {
animalMultimap.put(animal.type, animal);
}
// Step 5: Print the Multimap to the console
System.out.println("Multimap: ");
animalMultimap.asMap().forEach((type, animalsOfType) ->
System.out.println("Type: " + type + " - Animals: " + animalsOfType)
);
}
}
Output:
Multimap: Type: Mammal - Animals: [Lion, Tiger] Type: Reptile - Animals: [Snake, Crocodile]
4. Step By Step Explanation
Step 1: Include the Guava library in your project for utilizing the Multimap.
Step 2: Define a simple Animal class with name and type as attributes.
Step 3: Create and initialize a Set of Animal objects.
Step 4: Create an empty Multimap, then iterate through the Set of animals, and put each animal in the Multimap with the type as the key.
Step 5: Print the contents of the Multimap to the console, displaying the type of animal mapped to the set of animals of that type.