This week's book giveaway is in the Other Languages forum.We're giving away four copies of Functional Reactive Programming and have Stephen Blackheath and Anthony Jones on-line!See this thread for details.
Win a copy of Functional Reactive Programming this week in the Other Languages forum!

Which data structure for sorting a list of numbers and associated objects?

Rebecca Witmer
Ranch Hand
Posts: 46
Okay, now I have yet another question. I am trying to solve a simple problem. I have pairs of values in my TreeMap right now. I'm not sure I'm using the right data structure at all. I put them in a TreeMap because it allows you to maintain the mapping between two values and also to sort on the keys. What I have done so far is to sort the TreeMap and print it all out. I did this with code that uses and iterator that I found online. I don't totally understand it. I read the javadocs on iterators, though, but there doesn't seem to be an answer there. What I want to do is assign the values in the last five elements of the TreeMap to individual variables so that I can use them elsewhere. But how do you get at "last five" in a TreeMap? I see there's a method for getting the last element and one for removing an element. So I could theoretically get the last one and remove it five times. But that seems a little tacky. Is there a better way using the iterator? Am I even using the appropriate data structure? This is a really simple problem that seems to have an elusive answer.
Thanks for any ideas,
Rebecca

Eric Weinberg
Greenhorn
Posts: 18
well what i would do is just biggy bag one of your other loops. Like your print function. or your search function. While your in one of those loops set your variables.

so like if you have
for(int i=0; i<length; i++) //print function
if i is 5 away from the end
var1 = value
var2 = value

or whatever. the logic is there (i think) just fill in the langauge parts

thats how id' do it, then again i'm in the beginer section for a reason

Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
Take a look at the keySet() method. What does that return? Look at that class. Can you turn the keySet into something that makes it easier to get the last 5?

Is your assignment "the last 5" or "the 5 highest keys" ? If it's the latter, look at all the TreeSet constructors. You could make the TreeSet sort backwards, and then take the first 5!

I can think of one other really inefficient way to do this. I'm sure there are more. Let us know what you come up with!