Gooze_Berry
Gooze_Berry

Reputation: 95

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?

Upvotes: 0

Views: 118

Answers (1)

Ryuzaki L
Ryuzaki L

Reputation: 40058

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.

Upvotes: 4

Related Questions