Home » Collections » Hinzufuegen zu mapped Liste (:Map.computeIfAbsent)

Hinzufuegen zu mapped Liste (:Map.computeIfAbsent)

Eine Liste innerhalb einer Map erweitern falls sie schon vorhanden ist oder sonst neu erstellen:

    private Map<Object, List<Object>> addToMappedList1(Map<Object, List<Object>> mapOfLists, Object key, Object newValue){

        if (mapOfLists.get(key) == null){
            mapOfLists.put(key, new ArrayList<>());
        }
        mapOfLists.get(key).add(newValue);
        return mapOfLists;
    }

Eleganter:

    private Map<Object, List<Object>> addToMappedList2(Map<Object, List<Object>> mapOfLists, Object key, Object newValue){

        mapOfLists.computeIfAbsent(key, k -> new ArrayList<>()).add(newValue);
        return mapOfLists;
    }

Hinterlasse einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert