6 Replies - 246 Views - Last Post: 02 October 2012 - 06:40 PM Rate Topic: -----

#1 aquafatz  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • 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  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 432
  • View blog
  • Posts: 1,020
  • 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?
Was This Post Helpful? 0
  • +
  • -

#3 fromTheSprawl  Icon User is offline

  • Monomania
  • member icon

Reputation: 513
  • View blog
  • Posts: 2,055
  • 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.
Was This Post Helpful? 1
  • +
  • -

#4 aquafatz  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • 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!
Was This Post Helpful? 0
  • +
  • -

#5 pbl  Icon User is offline

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

Reputation: 8315
  • View blog
  • Posts: 31,836
  • 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);
:)
Was This Post Helpful? 0
  • +
  • -

#6 aquafatz  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • 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);
				BufferedReader br = new BufferedReader(new InputStreamReader(in));
				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
		}
	}
}



Was This Post Helpful? 0
  • +
  • -

#7 aquafatz  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • 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);
				BufferedReader br = new BufferedReader(new InputStreamReader(in));
				String strLine;
				while ((strLine = br.readLine()) != null)
				{
					String[] words = strLine.split("\\s+");
					for (int i = 0; i < words.length; i++)
					{
							//operations on words[]
							//add to map
							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 }
  	}
  }
}
 




Was This Post Helpful? 0
  • +
  • -

Page 1 of 1