java - 获取 LinkedHashMap 中每个条目的最后一个元素?

标签 java dictionary java-8

我有一个 map ,我想从该 map 中提取每个键的最后一个值,但我无法获取:

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"
    }
}

摘录:

dificultad=NUM
nivel=NUM

即每个键的最后 NUM 个条目

最佳答案

您可以使用 reduceMap<String,String> 中提取最后一个值然后使用 toMap 收集它们进入LinkedHashMap保存广告订单

但作为保留顺序的注释,您必须使用 LinkedHashMap也用于输入和输出

    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));

关于java - 获取 LinkedHashMap 中每个条目的最后一个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68461609/

相关文章:

java - LibGDX 中 music.class 的 TweenAccessor

java - 将列表 <Integer> 处理到线程

java.io.FileNotFoundException :/tomcat/lib/webservices-api. jar

python - 如何检查字典中的列表是否是键?

java - 在java 8中将拖动的组件添加到JPanel

java - ReSTLet : Unable to find a converter for this representation : [application/json, UTF-8]

python - 将元组列表转换为字典列表

python - Pandas 多索引/标题数据框到嵌套字典

java - 使用 Java 8 迭代 Map<String,Object> 数组并返回 Map<Long,Long>

java - 为什么我的音频播放会卡住ActionListners?