In this post I will show you a simple and easy way of working with JAVA Maps, more precisely, how to add an element (a.k.a value) to a multi nested maps:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
public void addElementToMap(Map<Long, Map<String, Map<Short, List<SomeDto>>>> map, SomeDto dto) { // get the first inner map Map<String, Map<Short, List<SomeDto>>> someMap = map.get(dto.gePrimaryKey()); if(someMap == null){ someMap = new HashMap<>(); map.put(dto.gePrimaryKey(), someMap); } // get the second inner map Map<Short, List<SomeDto>> otherMap = someMap.get(dto.getSomeId()); if(otherMap == null){ otherMap = new HashMap<>(); someMap.put(dto.getSomeId(), otherMap); } // get the inner list List<SomeDto> someList = otherMap.get(dto.getOtherId()); if(someList == null){ someList = new ArrayList<>(); otherMap.put(dto.getOtherId()), someList); } // add dto to the list someList.add(dto); } |
That’s it. Simple, isn’t it? 😉
Source code: github