Issue
I have a HashMap and assign key-value pairs to variable as shown below:
Map<UUID, EmployeeDTO> result = employeeService.getEmployees(employeeUuids);
UUID key = result.entrySet().iterator().next().getKey();
EmployeeDTO value = result.entrySet().iterator().next().getValue();
However, I am not sure about what is a proper way to assign multiple values from this HashMap. I thought a loop of course, but for naming variables, maybe there would be a better approaches. Any idea?
map.forEach((k, v) -> {
UUID key1 = k;
EmployeeDTO value1 = v;
// what about the other values?
UUID key2 = k;
EmployeeDTO value2 = v;
});
Solution
You cannot create variables without knowing the size of the map, so you need to store the keys and the values in two separate data structures, for example List
:
List<UUID> keys = new ArrayList<>();
List<EmployeeDTO> values = new ArrayList<>();
map.forEach((k, v) -> {
keys.add(k);
values.add(k);
});
In case the size of the map is known, you can store the entries in a list and assign the corresponding keys and values:
List<Map.Entry<UUID, EmployeeDTO>> entriesList = new ArrayList<>(map.entrySet());
UUID key1 = entriesList.get(0).getKey();
EmployeeDTO value1 = entriesList.get(0).getValue();
UUID key2 = entriesList.get(1).getKey();
EmployeeDTO value2 = entriesList.get(1).getValue();
// etc.
Obviously you need to do that for each key/value. It is theoretically possible to use a loop and some nasty reflection on the object that holds the variables, but this will do way more harm than good.
Answered By - Ivaylo Toskov
Answer Checked By - Terry (JavaFixing Volunteer)