Program that convert from Map to List in several ways.
There are several cases based on the desired result:
- List contain Map.Entry.
- List is created from the map keys only. In this example Integer keys
- List is created from the map values. In this example it is String list
- List which is created from map steam use Stream.map method to custom created record Elements.
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
// Java 17 record. Just simplified java POJO
// For simplicity we add it here. Normally for each
// class and record new file with the same name
// should be created
record Element(Integer k, String v) {};
public class MainConvertMapToList {
public static void main(String[] args) {
Map<Integer, String> map = Map.of(1, "A", 2, "B", 3, "C");
// Create list with map entries
List<Map.Entry<Integer, String>> listMapEntries = map.entrySet().stream().toList();
System.out.println("List with map entries: " + listMapEntries);
// Create list only with map Keys
List<Integer> listWithMapKeys = map.keySet().stream().toList();
System.out.println("List only with map keys: " + listWithMapKeys);
// Create list only with map values
List<String> listWithMapValues = map.values().stream().toList();
System.out.println("List only with map values: " + listWithMapValues);
// map and create objects from Element and add the to list
List<Element> listWithCustomElements = map
.entrySet()
.stream()
.map((entry) -> new Element(entry.getKey(), entry.getValue()))
.collect(Collectors.toList());
System.out.println("List with Elements objects with map data:" + listWithCustomElements);
}
}
Output:
List with map entries: [1=A, 2=B, 3=C]
List only with map keys: [1, 2, 3]
List only with map values: [A, B, C]
List with Elements objects with map data:[Element[k=1, v=A], Element[k=2, v=B], Element[k=3, v=C]]