繁体   English   中英

哈希表<String,List<String> &gt; 到 HashMap <Object,List<String> &gt; 使用流

[英]HashMap<String,List<String>> to HashMap<Object,List<String>> using streams

我有一个 HashMap,它包含一个键:字符串(对象名称被实例化)和值:列表(实例化对象的变量)

我目前的方法:

public Map<Room,List<String>> buildRoomObjects(Map<String,List<String>> map){

        List<Room> rooms = map.keySet().stream().map(Room::new).collect(Collectors.toList());

        Map<Room,List<String>> newmap = new HashMap<>();

        for ( Room room : rooms){

            newmap.put(room,map.get(room.getName()));
        }

       return  newmap;
    }

我可以避免在此处使用增强的 for Loop 并将其压缩为单个流吗?

您可以流式传输entrySet ,然后使用Collectors.toMap 使用 lambda 表达式entry -> new Room(entry.getKey())Room映射为键然后对应的值

Map<Room, List<String>> newmap = map.entrySet().stream()
            .collect(Collectors.toMap(entry -> new Room(entry.getKey()), Map.Entry::getValue));

如果您可能有任何重复的键,那么您可以将toMapBinaryOperator toMap使用

如果映射的键包含重复项(根据 Object.equals(Object)),则在执行集合操作时会抛出 IllegalStateException。 如果映射的键可能有重复项,请改用toMap(Function, Function, BinaryOperator)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM