This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Java Interview Guide and have Anthony DePalma on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes TreeMap question#2 Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "TreeMap question#2" Watch "TreeMap question#2" New topic

TreeMap question#2

Anthony Alexander

Joined: Feb 16, 2006
Posts: 15
Say I have two treemaps A and B defined as : <String, Integer>


Tree Map A
apple, 4
orange, 2

Tree Map B
banana, 3
orange, 1

How do I search for identical keys (orange in this example) and use the values for each key (eg. 2 + 1 = 3)?

Do I have to loop through every treemap looking at every key?
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2398
If you look at the API for TreeMap, there is a method keySet which will return a Set containing the keys in the TreeMap.

In the Set interface there is a specification for the method retainAll which will produce the intersection of two sets.
Garrett Rowe
Ranch Hand

Joined: Jan 17, 2006
Posts: 1296
If you are only interested in keys that are identical to both TreeMaps then you can use the retainAll() method.

Assumiing you have two treeMaps that you want to find the identical keys for.

Some problems are so complex that you have to be highly intelligent and well informed just to be undecided about them. - Laurence J. Peter
Anthony Alexander

Joined: Feb 16, 2006
Posts: 15
Yes. Yes. Good idea. that may work. thanks.
I agree. Here's the link:
subject: TreeMap question#2
It's not a secret anymore!