Java 7 to Java 8: Steps after getting default value from hashmap and then updating underlying map if not null?

Solution for Java 7 to Java 8: Steps after getting default value from hashmap and then updating underlying map if not null?
is Given Below:

I previously had a piece of old school code that looked like this prior to Java 8:

List<Person> databaseListOfPersons = ... //random list of Person object

Map<String, List<Person>> somePersonListLookup = new HashMap<>();
...
for (Person person: databaseListOfPersons) {
     List<Person> personList = somePersonListLookup.get(person.getId());

     if (personList == null) {
          personList = new ArrayList<>();
          somePersonListLookup.put(person.getId(), personList);
     }
     personList.add(person)
}

The getId() method for the Person class would just return A, B, or C as a simple string. This block of code pretty much checked if there was an existing id key available, and if not then create a new entry and then add that person to the list of persons that was apart of the Map. If the id key was already and entry, then to just add that person to the list and it would update the value to the already existing key, further increasing the list of people with the same id key.

So I want to just update the code to Java 8 and keep up with times and I have the old code converted to this:

List<Person> personList = somePersonListLookup.computeIfAbsent(person.getId(), x -> new ArrayList<>());

personList.add(person);

My question is: is this proper? It feels weird having a list initialized and not being used and then having the personList add the object like previously.

Yes, your code is proper, it’s fine.

You may want to take it a step further and use a stream operation. Simple version:

    somePersonListLookup = personList.stream()
            .collect(Collectors.groupingBy(Person::getId));

As you can see, this assigns a new map to somePersonListLookup thus discarding any content that it may already have. If you need to preserve old content or just need to preserve the same map because other references to it may exist, stick to the code you have already written. As i said, it’s fine.