Sobes.tech
Junior

Is it possible to convert a collection into a Map?

sobes.tech AI

Answer from AI

Yes, it is possible.

Main methods of transformation:

  1. Using Stream API (Java 8+): The most flexible and recommended way. Allows setting keys and values for Map elements, as well as handling duplicate keys.
  2. Using a loop: A classic approach suitable for any Java version. Less functional but more explicit control.

Examples:

Stream API

Transforming List<Pojo> into Map<Integer, String>, where the key is id, and the value is name.

// Assume we have a class Pojo and a list of Pojo objects
// class Pojo { int id; String name; public int getId() { return id; } public String getName() { return name; }}
List<Pojo> pojoList = new ArrayList<>();
pojoList.add(new Pojo(1, "Alice"));
pojoList.add(new Pojo(2, "Bob"));
pojoList.add(new Pojo(3, "Charlie"));

// Transformation using Collectors.toMap
Map<Integer, String> pojoMap = pojoList.stream()
        .collect(Collectors.toMap(Pojo::getId, Pojo::getName));

// Handling duplicate keys (e.g., keep the last value)
Map<Integer, String> pojoMapWithDuplicates = pojoList.stream()
        .collect(Collectors.toMap(Pojo::getId, Pojo::getName, (oldValue, newValue) -> newValue));

// Getting a Map with a specific implementation (e.g., LinkedHashMap)
Map<Integer, String> linkedPojoMap = pojoList.stream()
        .collect(Collectors.toMap(Pojo::getId, Pojo::getName, (oldValue, newValue) -> newValue, LinkedHashMap::new));

Loop

Transforming the same List<Pojo> into Map<Integer, String>.

List<Pojo> pojoList = new ArrayList<>();
pojoList.add(new Pojo(1, "Alice"));
pojoList.add(new Pojo(2, "Bob"));

Map<Integer, String> pojoMap = new HashMap<>();
for (Pojo pojo : pojoList) {
    // Null key or value check may be needed depending on conditions
    if (pojoMap.containsKey(pojo.getId())) {
        // Handling duplicate key, e.g., throw exception, overwrite, or ignore
        System.out.println("Duplicate key: " + pojo.getId());
        // throw new IllegalArgumentException("Duplicate key");
    }
    pojoMap.put(pojo.getId(), pojo.getName());
}

Choice of method:

  • Stream API is preferred for most modern Java cases as it is more expressive and functional, especially when handling duplicate keys or transforming values/keys.
  • Loop is useful if more explicit control over the process is needed or when working with older Java versions (<8).

It is important to consider possible conflicts when duplicate keys exist in the source collection during transformation to Map, as Map cannot contain duplicate keys. The Stream API provides various strategies for resolving such conflicts.

Is it possible to convert a collection into a Map… - sobes.tech