1 Replies - 569 Views - Last Post: 19 July 2012 - 05:04 PM Rate Topic: -----

#1 KaptainCavy  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 13
  • Joined: 25-June 12

display the words in ascending order

Posted 19 July 2012 - 03:27 PM

Currently I have the following code.
I want to display the words in ascending order of occurrence counts.
In addition I would like to simplify my main method.

Any suggestions? Thanks.

// import
import java.util.*;
import java.io.*;

// program
public class Program 
{
	// main
	public static void main(String[] args) throws IOException 
	{
		try
		{

			// read file, file is passed as argument
			BufferedReader read = (new BufferedReader(new FileReader(args[0])));
			
			// declare variables 
			String stream = null;
			TreeMap<String,Integer> store = new TreeMap<String,Integer>();
			
			// count words in case-insensitive fashion, do not count 
			// word if the first character is not a letter
			while ((stream = read.readLine()) != null)
			{
				// delimited special characters and spaces 
				String[] text = stream.split("[ ,:.:?'\"()]");
				
				for (int i = 0; i < text.length; i++)
				{
					String token = text[i].toLowerCase();
					
					if (token.length() > 0)
					{
						if (store.get(token) == null)
						{
							store.put(token,1);
						}
						else
						{
							int val = store.get(token).intValue();
							val++;
							store.put(token,val);
						}
					}
				}
			}
			
			// display output in alphabetical order of words with each 
			// proceeded by its occurrence count
			
			// put entries in set
			Set<Map.Entry<String,Integer>> entrySet = store.entrySet();
			
			// get token and val from each entry
			System.out.println("\nCount:\t"+ "\tWords:\n");
			for (Map.Entry<String,Integer> entry: entrySet)
			{
			System.out.println(entry.getValue() + "\t\t" + entry.getKey());
			}
			
			// display the words in ascending order of occurrence counts
			
			
		}
		catch (Exception x)
		{
			x.printStackTrace();
		}
	}
}



Is This A Good Question/Topic? 0
  • +

Replies To: display the words in ascending order

#2 blackcompe  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1009
  • View blog
  • Posts: 2,186
  • Joined: 05-May 05

Re: display the words in ascending order

Posted 19 July 2012 - 05:04 PM

A TreeMap maintains a sorted ordering on keys, not values. See How to sort Map by value. I suggest using the first option.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1