Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVA

add value to hashmap with list as value java

// Good implementation
for (CityRecord city_record: allRecords) {
	city_map.computeIfAbsent(city_record.city(), k -> new ArrayList<>()).add(city_record)
}

// Verbose implementation			
for (CityRecord city_record: allRecords) {
	List<CityRecord> value_list = city_map.get(city_record.city());
	// if list does not exist, create it
	if(value_list == null) {
		value_list = new ArrayList<CityRecord>();
		value_list.add(city_record);
		city_map.put(city_record.city(), value_list);
	} else {
		// add if item is not already in list
		city_map.get(city_record.city()).add(city_record);
	}
}
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #add #hashmap #list #java
ADD COMMENT
Topic
Name
3+4 =