ordering of items in a treemap

A

angelochen960

Hi,

I have code:

TreeMap<String, String> shoeSize = new TreeMap<String, String>();

shoeSize.put("8", "8");
shoeSize.put("8.5", "8.5");
shoeSize.put("10", "10");
System.out.println(shoeSize.toString());

I got:

{10=10, 8=8, 8.5=8.5}

I'd like to get the order same inserted:

{8=8, 8.5=8.5, 10=10}

any idea? thanks
 
D

Donkey Hot

Hi,

I have code:

TreeMap<String, String> shoeSize = new TreeMap<String, String>();

shoeSize.put("8", "8");
shoeSize.put("8.5", "8.5");
shoeSize.put("10", "10");
System.out.println(shoeSize.toString());

I got:

{10=10, 8=8, 8.5=8.5}

I'd like to get the order same inserted:

{8=8, 8.5=8.5, 10=10}

any idea? thanks

Why you keep the key as a String, as the key value seems to be a Float or
something?

Float would compare as you want, but a String of course not.

Make it a TreeMap<Float, String> shoeSize
 
V

voorth

On Apr 8, 10:22 am, Andrea Francia ; they'll work just fine without
that.
If you don't subclass the TreeMap how you can create a Comparator that
compare keys in insertion order?

For insertion order, you use LinkedHashMap instead of TreeMap.

I think the OP just wanted "natural" ordering, however. You have to
write a Comparator for that.

Henk
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top