Search code examples
javahashmapkeydto

How to extract the value with the key field in hashmap


Map<string,DTO> DTOmap

The hash map has string as the key and the DTO as the value field in a hashmap I am trying to get the DTO values printed in an excel sheet.
Can I use

Set<string> rows=DTOmap.keyset();
For(string key:rows)
Object[] objArr =DTOmap. Get(key);
For (Object obj:objArr){
Cell cell=row.createCell(cellnum++);

Can I use the above method to get all the DTO values using the key field to extract it?


Solution

  • for(string key:rows){
     Object[] objArr =DTOmap.get(key);
    }
    

    This is invalid. Your map is Map<string,DTO> , by calling .get(key) you will get a single DTO instance not an array of it. You need to store all the DTO instances in an array / List for all keys. Something like this :

    List<DTO> list = new ArrayList<>();
    for(String key:rows){
     DTO dto = DTOmap.get(key);
     list.add(dto);
    }
    

    After that you can do whatever you want iterating the list.

    for(DTO dto : list){
     //your code 
    }
    

    EDIT: As mentioned by @f1sh in the comments .You can do the same just by iterating the map.keyset()

    for(String key : DTOmap.keyset()){
     DTO dto = DTOmap.get(key);
    
     //your code
     Cell cell=row.createCell(cellnum++);
    }
    

    It is pointless to use two for-loop to perform some operation which can be done in one.