Tuesday, November 26, 2024

Map to List Using Guava

Suppose, we have a list of Employee objects where we want to create a Map from the list with employee id as Key. You can do that with Java Stream, but with Guava the code becomes more concise. Below is the example:

Add Guava in Maven dependency:

<dependency>

    <groupId>com.google.guava</groupId>

    <artifactId>guava</artifactId>

    <version>33.3.1-jre</version>

</dependency>

@Data

public class Employee() {

private int id;

private String name;

}

Map<Integer, Employee> employeeMap = Maps.uniqueIndex(employeeList, Employee::id);

If you want to create Map<Integer,List<Employee>> then use below

ImmutableListMultimap<Integer, Employee> employeeMap = Multimaps.index(employeeList, Employee::id);


https://howtodoinjava.com/java/collections/convert-list-to-map/


Map to List Using Guava

Suppose, we have a list of Employee objects where we want to create a Map from the list with employee id as Key. You can do that with Java S...