简体   繁体   中英

HashMap<String,List<String>> to HashMap<Object,List<String>> using streams

I have a HashMap which contains a key: String ( name of object be instantiated ) and Value: List ( variables for the instantiated object)

My current method :

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

Can I avoid the use of the enhanced for Loop here and condense to a single stream?

You can stream the entrySet and then use Collectors.toMap . Use the lambda expression entry -> new Room(entry.getKey()) to map Room as key and then corresponding value

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

In case if you might have any duplicates keys then you can use toMap with BinaryOperator

If the mapped keys contains duplicates (according to Object.equals(Object)), an IllegalStateException is thrown when the collection operation is performed. If the mapped keys may have duplicates, use toMap(Function, Function, BinaryOperator) instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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