1. Introduction
Converting a List to a Map in Java is a frequent requirement when dealing with collections. It is especially useful when we need fast lookups to map keys to their associated values. In this tutorial, we’ll demonstrate how to convert a List of objects into a Map using Java’s Stream API.
2. Program Steps
1. Import necessary libraries.
2. Create a class Product with fields id and name.
3. Initialize a List of Product objects.
4. Convert the List to a Map using the stream() method and Collectors.toMap() function.
5. Print the resultant Map.
3. Code Program
// Step 1: Import necessary libraries
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.Arrays;
// Step 2: Create a class Product with fields id and name
class Product {
int id;
String name;
public Product(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
}
public class ListToMapExample {
public static void main(String[] args) {
// Step 3: Initialize a List of Product objects
List<Product> productList = Arrays.asList(
new Product(1, "Apple"),
new Product(2, "Banana"),
new Product(3, "Cherry")
);
// Step 4: Convert the List to a Map using the stream() method and Collectors.toMap() function
Map<Integer, String> productMap = productList.stream()
.collect(Collectors.toMap(Product::getId, Product::getName));
// Step 5: Print the resultant Map
System.out.println("Product Map: " + productMap);
}
}
Output:
Product Map: {1=Apple, 2=Banana, 3=Cherry}
4. Step By Step Explanation
Step 1: Import the necessary libraries for working with lists, maps, streams, and collectors.
Step 2: Define a Product class with fields id and name and their corresponding accessor methods.
Step 3: Initialize a List named productList containing several Product objects.
Step 4: Use the stream() method to convert the List to a Stream, then call collect() on the stream, passing Collectors.toMap() with method references to Product::getId and Product::getName as arguments, to collect the elements of the stream into a Map.
Step 5: Print the resultant Map which contains the product IDs as keys and product names as values.