Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to assign multiple value from HashMap to variables in Java?

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;
});

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading