Can
Can

Reputation: 4726

Resorting a TreeMap in Java

I searched the web(and Stackoverflow) a lot but couldn't exactly found what I was looking for. Also couldn't really understand the concept.

As a Java assignment I have a treeMap storing some values in it.

static Map<String, Double> customers = new TreeMap<String, Double>();

Naturally it stores them ascending by it's String values. But I want it to store it's values ascending by it's Double values. How can I achieve this by a comparator? Details would be much appreciated.

Also again in this assignment I've another, separate treeMap which stores different values. Again declared like below:

static Map<String, Double> customers = new TreeMap<String, Double>();

It's okay for it to store it's values ascending by String. I'm using it like this to print out it's values but I also need to print it's values in ascending order sorted by Double. So how can I re-sort a treeMap. Again, details would be much appreciated.

Upvotes: 1

Views: 2306

Answers (2)

icyrock.com
icyrock.com

Reputation: 28598

Make another map:

Map<Double, String> values = new TreeMap<Double, String>();

and always add to both maps (e.g. via a helper method). Unless there are memory constraints, you will get your customers maps sorted by customer and values sorted by whatever the Double value represents.

If you can have duplicate values, you can make a list (or a set, depending on the requirements) of customers instead:

Map<Double, List<String>> values = new TreeMap<Double, List<String>>();

Upvotes: 1

Matt Ball
Matt Ball

Reputation: 359786

You cannot re-sort a TreeMap. It has a fixed iteration order, determined at TreeMap construct-time. If you want a different sort order, use a different data structure.

I'm using it like this to print out it's values but I also need to print it's values in ascending order sorted by Double.

So don't worry about sorting the TreeMap. Create a List<Double> of the values in the map, and sort those.

List<Double> values = new ArrayList<Double>(customers.values());
Collections.sort(values);
System.out.println(values);

Upvotes: 2

Related Questions