I have a map and I want to extract the last value for each key from that map, but I can’t get it:
import java.util.LinkedHashMap; import java.util.Map; class MyTestClass { private static final String almacenNombreClase = "Professor"; private static final String TXT = "TXT"; private static final String NUM = "NUM"; public static void main(String[] args) { Map<String, Map<String, String>> mapNombreClaseYPropiedades = new LinkedHashMap<>(); mapNombreClaseYPropiedades.put("Professor", Map.of("texto", TXT, "tipo", TXT, "prueba", NUM, "dificultad", NUM )); mapNombreClaseYPropiedades.put("Exam", Map.of("texto", TXT, "nivel", NUM )); //values of mapNombreClaseYPropiedades Map<String, String> valores = mapNombreClaseYPropiedades.get(almacenNombreClase); valores.forEach((k, v) -> { // Here I want to check the last element of each entry if (v instanceof String ) { System.out.println("String " + k + ","); } else { System.out.println("Integer " + k + ","); } }); // I want to see output "dificultad=NUM" "nivel=NUM" } }
Extract:
dificultad=NUM nivel=NUM
i.e. the last NUM entries for each key
Advertisement
Answer
You can use reduce to extract the last value from Map<String,String>
and then collect them using toMap into LinkedHashMap
to save the insertion order
But as a note to preserve the order you have to use LinkedHashMap
for input and output as well
Map<String,String> valores = mapNombreClaseYPropiedades.values() .stream() .map(map->map.entrySet().stream().reduce((prev,next)->next)) .filter(Optional::isPresent) .map(Optional::get) .collect(Collectors.toMap(Map.Entry::getKey,Map.Entry::getValue, (prev,next)->next,LinkedHashMap::new));