0

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?

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.