Lambda expressions provide a concise way to perform operations on collections without writing boilerplate loops. Using lambdas, an ArrayList can be easily converted into a HashMap by mapping each element to a key–value pair.
Syntax
(parameters) -> expression
Example: Converting an ArrayList containing objects into a HashMap where: One field acts as the key, and Another field acts as the value.
Input : List : [1="I", 2="love", 3="Geeks" , 4="for" , 5="Geeks"]
Output: Map : {1=I, 2=Love, 3=Geeks, 4=For, 5=Geeks}
Approach
- Create a list containing objects with key–value data.
- Create an empty HashMap.
- Iterate over the list using a lambda expression.
- Insert elements into the map using map.put(key, value).
- Print the resulting map.
import java.util.*;
class ListItems {
private Integer key;
private String value;
public ListItems(Integer key, String value) {
this.key = key;
this.value = value;
}
public Integer getKey() {
return key;
}
public String getValue() {
return value;
}
}
class Main {
public static void main(String[] args) {
List<ListItems> list = new ArrayList<>();
list.add(new ListItems(1, "I"));
list.add(new ListItems(2, "Love"));
list.add(new ListItems(3, "Geeks"));
list.add(new ListItems(4, "For"));
list.add(new ListItems(5, "Geeks"));
Map<Integer, String> map = new HashMap<>();
list.forEach(item ->
map.put(item.getKey(), item.getValue())
);
System.out.println("Map : " + map);
}
}
Output
Map : {1=I, 2=Love, 3=Geeks, 4=For, 5=Geeks}
Explanation
- Each object in the ArrayList contains a key and a value.
- The forEach() method iterates over the list.
- The lambda expression inserts each element into the HashMap.
- This approach replaces a traditional for loop with cleaner and more readable code.
Note:
- If duplicate keys exist, the latest value will overwrite the previous one.
- This approach is best suited when keys are already available in the list objects.
- Java 8 Streams (Collectors.toMap) can also be used for the same task.