Elyas
Elyas

Reputation: 65

How to initialise a Map<K, Map<K,V>> on a single line

Is it possible to combine these two lines of code into one?

    allPeople.put("Me", new HashMap<String, String>());
    allPeople.get("Me").put("Name", "Surname");

Upvotes: 2

Views: 1642

Answers (3)

Bax
Bax

Reputation: 4476

Starting with Java 9 there is a JDK provided Map factory

allPeople.put("Me", Map.of("Name", "Surname"));

Upvotes: 4

user5063151
user5063151

Reputation:

You should probably represent a person as an object. That way you cannot call get("someKey") on a key that does not exist and your code blow up. That is the idea of object oriented programming. To encapsulate related data and functionality. Nested maps does a similar thing, but it is more error prone. For a language that does not support objects, that makes sense. But representing a person as an object allows you to better control the fields the mapping has, thus making your code more error-free.

class Person {
    private String name;
    private String surname;

    public Person(String name, String surname) {
        this.name    = name;
        this.surname = surname;
    }

}

Then you create a map that maps names to people:

Map<String, Person> allPeople = new HashMap<>();

// Create an object that represents a person
Person me = new Person("name", "surname");

// Map the string "me" to the object me that represents me
allPeople.put("ME", me);

Upvotes: 2

Andy Turner
Andy Turner

Reputation: 140318

The literal replacement of these two lines would be (in Java 8+):

allPeople.compute("Me", (k, v) -> new HashMap<>()).put("Name", "Surname");

or, in the style of Bax's answer, for pre-Java 9, you could use:

allPeople.put("Me", new HashMap<>(Collections.singletonMap("Name", "Surname")));

Upvotes: 5

Related Questions