# Sort the values in a map-Sorting incorrectly

Page 1 of 1

## 6 Replies - 455 Views - Last Post: 02 October 2012 - 06:40 PMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'http://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=293926&amp;s=0ce735bf549b953fc40c3fed538b1bdf&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 aquafatz

Reputation: 0
• Posts: 19
• Joined: 23-September 12

# Sort the values in a map-Sorting incorrectly

Posted 01 October 2012 - 11:09 PM

I want to sort a map in decreasing order based on the values.
I have written a temporary test code.
But it is giving the incorrect result.
Could you please tell me where I am making a mistake?

```package FirstTry;
import java.util.*;
public class SortingMap
{

public static void main(String[] args)
{
Map<String, Double> unsorted = new HashMap<String, Double>();
unsorted.put("a", 100.0);
unsorted.put("b", 55.0);
unsorted.put("c", 200.0);
unsorted.put("d", 55.0);

Comparator<String> compare = new Comparator<String>()
{

public int compare(String o1, String o2)
{
return o1.compareTo(o2);
}
};

Map<String, Double> sorted = new TreeMap<String, Double>(compare);
sorted.putAll(unsorted);
System.out.println(sorted);
}
}

```

Is This A Good Question/Topic? 0

## Replies To: Sort the values in a map-Sorting incorrectly

### #2 Sheph

• D.I.C Lover

Reputation: 444
• Posts: 1,030
• Joined: 12-October 11

## Re: Sort the values in a map-Sorting incorrectly

Posted 02 October 2012 - 01:00 AM

How does the result that this code would give differ from the result you expect? For example: Are the values sorted in ascending order instead of descending?

### #3 fromTheSprawl

• Monomania

Reputation: 514
• Posts: 2,063
• Joined: 28-December 10

## Re: Sort the values in a map-Sorting incorrectly

Posted 02 October 2012 - 01:06 AM

It only sorts the keys, according to the TreeMap specification:

Quote

java.util.TreeMap.TreeMap<String, Double>(Comparator<? super String> comparator)

TreeMap
public TreeMap(Comparator<? super K> comparator)
Constructs a new, empty tree map, ordered according to the given comparator. All keys inserted into the map must be mutually comparable by the given comparator: comparator.compare(k1, k2) must not throw a ClassCastException for any keys k1 and k2 in the map. If the user attempts to put a key into the map that violates this constraint, the put(Object key, Object value) call will throw a ClassCastException.

Parameters:
comparator - the comparator that will be used to order this map. If null, the natural ordering of the keys will be used.
--------------------------------------------------------------------------------

So I guess you need to modify it to sort the values instead.

### #4 aquafatz

Reputation: 0
• Posts: 19
• Joined: 23-September 12

## Re: Sort the values in a map-Sorting incorrectly

Posted 02 October 2012 - 05:18 AM

Ok..I'll try again! Thanks!

### #5 pbl

• There is nothing you can't do with a JTable

Reputation: 8362
• Posts: 31,955
• Joined: 06-March 08

## Re: Sort the values in a map-Sorting incorrectly

Posted 02 October 2012 - 12:20 PM

Decrasing order should be
return o2.compareTo(o1);

### #6 aquafatz

Reputation: 0
• Posts: 19
• Joined: 23-September 12

## Re: Sort the values in a map-Sorting incorrectly

Posted 02 October 2012 - 01:15 PM

@pbl....thanks! But for what I want, my logic is wrong.

I changed the logic but I am getting this error. Can't understand the mistake. Could you please guide me?

Error:
No enclosing instance of type FirstTry3 is accessible. Must qualify the allocation with an enclosing instance of type FirstTry3 (e.g. x.new A() where x is an instance of FirstTry3).

P.S. I have just included the code I think might be needed and not the entire code.

```package FirstTry;

/*import*/

public class FirstTry3
{
public static void main(String[] args)
{
try
{
double nowords = 0;
Integer ONE = new Integer(1);

HashMap<String, Integer> map = new HashMap<String, Integer>();
ValueComparator bvc = new ValueComparator(map);
TreeMap<String, Integer> sorted_map = new TreeMap<String, Integer>(bvc);

File dir = new File(
"name of dir");
for (File fn : dir.listFiles())
{
FileInputStream fstream = new FileInputStream(fn);
DataInputStream in = new DataInputStream(fstream);
String strLine;
while ((strLine = br.readLine()) != null)
{
/*operations on words[]*/

map.put(words[i], frequency);
}

}
// System.out.println(map);
br.close();
in.close();
}
System.out.println(map);
System.out.println(sorted_map);
System.out.println(nowords + " total words were found.");
System.out.println(map.size() + " distinct words were found.");

}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}

class ValueComparator implements Comparator<String>
{

Map<String, Integer> base;

public ValueComparator(HashMap<String, Integer> map)
{
this.base = map;
}

public int compare(String a, String B)/>
{
if (base.get(a) >= base.get(B)/>)
{
return -1;
}
else
{
return 1;
} // returning 0 would merge keys
}
}
}

```

### #7 aquafatz

Reputation: 0
• Posts: 19
• Joined: 23-September 12

## Re: Sort the values in a map-Sorting incorrectly

Posted 02 October 2012 - 06:40 PM

I found my mistake. I've made the changes.
But I think there is something wrong with my logic.
Because the 'sorted map' is empty {}. Whereas it should contain the elements of 'map' sorted in decreasing order by the values.
Thanks!

```package FirstTry;

import java.io.FileInputStream;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import java.io.*;

public class FirstTry3
{
public static void main(String[] args)
{
try
{
double nowords = 0;
Integer ONE = new Integer(1);

HashMap<String, Integer> map = new HashMap<String, Integer>();

File dir = new File(
"\\\\FATTU-PC\\Users\\Fattu\\workspace\\Tokenization\\Cranfieldtrial");
for (File fn : dir.listFiles())
{
FileInputStream fstream = new FileInputStream(fn);
DataInputStream in = new DataInputStream(fstream);
String strLine;
while ((strLine = br.readLine()) != null)
{
String[] words = strLine.split("\\s+");
for (int i = 0; i < words.length; i++)
{
//operations on words[]
map.put(words[i], frequency);

}// for i

}// while
br.close();
in.close();
}// for files
System.out.println("Unsorted map");
System.out.println(map);

ValueComparator bvc = new ValueComparator(map);
TreeMap<String, Integer> sorted_map = new TreeMap<String,Integer>(bvc);

System.out.println("sorted map");
System.out.println(sorted_map);

}//try
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}//main
}//class

class ValueComparator implements Comparator<String>
{

Map<String, Integer> base;

public ValueComparator(HashMap<String, Integer> map)
{
this.base = map;
}

public int compare(String a, String B)/>
{
if (base.get(a) >= base.get(B)/>)
{
return -1;
}
else
{
return 1;  // returning 0 would merge keys }
}
}
}

```