Results 1 to 4 of 4
- 08-16-2011, 08:20 PM #1
Member
- Join Date
- Aug 2011
- Posts
- 1
- Rep Power
- 0
display top ten occuring most words in a file
i have a program which displays no of occurances of all words in a file and also sorts it according to the number of occurances
How can I display only the top 10 of them?
Here is my program:
Java Code:import java.io.*; import java.util.*; public class HashMapEx { public static void main(String[] args) { LinkedHashMap<String, Integer> wordcount = new LinkedHashMap<String, Integer>(); try { BufferedReader in = new BufferedReader( new FileReader("c:\\test\\sample.txt")); String str; while ((str = in.readLine()) != null) { str = str.toLowerCase(); // convert to lower case int idx1 = -1; for (int i = 0; i < str.length(); i++) { if ((!Character.isLetter(str.charAt(i))) || (i + 1 == str.length())) { if (i - idx1 > 1) { if (Character.isLetter(str.charAt(i))) i++; String word = str.substring(idx1 + 1, i); if (wordcount.containsKey(word)) { wordcount.put(word, wordcount.get(word) + 1); } else { wordcount.put(word, 1); } } idx1 = i; } } } in.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } ArrayList<Integer> values = new ArrayList<Integer>(); values.addAll(wordcount.values()); Collections.sort(values, Collections.reverseOrder()); int last_i = -1; for (Integer i : values) { if (last_i == i) // without duplicates continue; last_i = i; for (String s : wordcount.keySet()) { if (wordcount.get(s) == i) // which have this value System.out.println(s + ":" + i); } } } }
Last edited by sunde887; 08-16-2011 at 08:32 PM. Reason: Added code tags, [code]...[/code]
- 08-16-2011, 08:34 PM #2
- Join Date
- Jan 2011
- Location
- Richmond, Virginia
- Posts
- 3,069
- Blog Entries
- 3
- Rep Power
- 12
Well if you sorted it, then you would display just the highest 10 results. If you sort it in reverse order(highest-lowest), the first 10 entries would be the items you want, otherwise it should be the last 10 entries.
- 08-17-2011, 01:56 AM #3
pls help me with word occurances program
Duplicate post.
- 08-17-2011, 07:34 AM #4
Similar Threads
-
display random words from a string
By Kenken in forum New To JavaReplies: 4Last Post: 04-02-2011, 01:38 PM -
windowClosed(WindowEvent e) occuring twice
By AndyV in forum AWT / SwingReplies: 3Last Post: 02-27-2011, 12:13 PM -
Display only certain contents of text file and edit display
By blkshrk81 in forum New To JavaReplies: 1Last Post: 12-01-2010, 06:35 PM -
Finding words (and more) in another file
By Lund01 in forum Java AppletsReplies: 5Last Post: 09-30-2010, 01:03 PM -
HELP ON errors occuring in the code
By jaiminparikh in forum Advanced JavaReplies: 6Last Post: 02-12-2009, 02:02 PM
Bookmarks