PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, September 20, 2022

[FIXED] How to extract the value with the key field in hashmap

 September 20, 2022     dto, hashmap, java, key     No comments   

Issue

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.



Answered By - Sayan Bhattacharya
Answer Checked By - Timothy Miller (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing