• Post Reply Bookmark Topic Watch Topic
  • New Topic

Hasmap having single key and mutiple value?  RSS feed

 
priyanaka jaiswal
Ranch Hand
Posts: 79
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
how to write Hashmap when key is loan id and values are person name and loan amount?that is one key and multiple value
 
Rob Spoor
Sheriff
Posts: 21133
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
priyanaka jaiswal wrote:please send me code

We are NotACodeMill.

The solution is pretty easy - instead of a HashMap<K,V>, where K is the key type and V is the value type, use a HashMap<K,List<V>> or a HashMap<K,Set<V>>. The insertion is also pretty easy:
- first get the value for the key which is a List<V> or Set<V>.
- if that does not exist, create a new one and add that to the map for the key.
- add to the List / Set.
 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
We don't just hand out code like that round here, but we'll help you work out your own solution.

My suggestion would be: you need a single object that encapsulates all the data related to a loan that you can add as the value. That suggests you define your own class to do that.

Edit: And welcome to The Ranch!
 
Rajkamal Pillai
Ranch Hand
Posts: 445
1
Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Use a bean to store multiple values (Loan ID, person name, loan amount e.t.c).

Key - Loan ID
Value - LoanNean (loanID, personName, loanAmount)
 
rob michael
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you dont want to code it yourself and have no aversion to existing libraries you can use the MultiMap implementation in Google's Collections library (now called guava):

http://code.google.com/p/guava-libraries/
http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/Multimap.html
http://www.factorypattern.com/multimap-in-google-collections-library/
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!