Multi-layered Hash in Java

2.5k views Asked by At

In Perl if I want to have a multi-layered hash, I would write:

$hash_ref->{'key1'}->{'key2'}='value';

Where 'key1' might be a person's name, 'key2' might be "Savings Account" (vs. "Checking Account") and 'value' might be the amount of money in the account.

Is there an equivalent to this in Java, i.e. access values via hash references? What's the syntax like for this? Any examples or other resource references would be greatly appreciated. Thanks!

5

There are 5 answers

3
Bozho On BEST ANSWER

You can have a Map<Map<..>>, where you'll be able to call map.get("key1").get("key2")

But note that Java is a statically-typed, object-oriented language. So you'd better creat classes: Person, SavingsAccount, and a Person has a field private SavingsAccount savingsAcount. Then you'll be able to do a compile-time safe: map.get("John").getSavingsAccount()

0
Bhesh Gurung On

You could create a class that represents the key with proper implementation for equals and hashCode methods:

1
JB Nizet On

In Java, we use objects. We would have a Person object, with a name property of type String, and a savingsAccount of type Account. This Account object would have a value property, of type BigDecimal.

Java is an OO language. It's not Perl. You should use Java idioms in Java, and not Perl idioms.

0
Liam On

I am not sure why the question was down-voted but to answer your question, in Java you can use nested Maps to achieve the same.

0
Savino Sguera On

For instance, you can have a

HashMap<String, HashMap<String, BigDecimal>>. 

I would not call it OOD, but you can.

It would probably be a bit more readable if you had a class for representing Person, a class to represent PersonalAccounts, which has Account instances as attributes, one for each account type (I assume those would be very few, otherwise a list would be better).

Then a single

HashMap<Person, PersonalAccounts> 

is enough, if you want to use an HashMap.

Actually you don't even need a map if an instance of PersonalAccounts is an attribute of a Person.