Working with nested Maps in JAVA

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:

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

Leave a Reply

Your email address will not be published. Required fields are marked *