Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.*;
- import java.util.*;
- import java.util.Map.Entry;
- public class WordUp {
- public static void main(String[] args){
- //readFile("src/john.txt");
- HashMap<String,Integer> hist = new HashMap<String,Integer> ();
- readCount("src/john.txt",hist);
- Map<String, Integer> sorted = sortByValues(hist);
- System.out.println("Sorted Map in Java by key: " + sorted);
- // -----------------------
- try{
- BufferedWriter out = new BufferedWriter(new FileWriter("src/output.txt"));
- for (Map.Entry<String, Integer> entry : sorted.entrySet()) {
- String key = entry.getKey();
- Integer value = entry.getValue();
- out.write(key + " = " + value + "\n");
- }
- out.close();
- }
- catch(Exception e){
- e.printStackTrace();
- }
- }
- public static void readFile (String filename){
- try{
- BufferedReader in = new BufferedReader(new FileReader(filename));
- for (String s = in.readLine(); s != null; s = in.readLine()){
- System.out.println(s);
- }
- in.close();
- }
- catch(Exception e){
- e.printStackTrace();
- }
- }
- public static void readCount (String filename, HashMap<String,Integer> h){
- try{
- BufferedReader in = new BufferedReader(new FileReader(filename));
- for (String s = in.readLine(); s != null; s = in.readLine()){
- String[] words = s.toLowerCase().split("[\\p{Punct}\\s\\d]+");
- for(String k:words){
- if (h.containsKey(k))
- h.put(k, h.get(k) + 1);
- else
- h.put(k, 1);
- }
- }
- in.close();
- }
- catch(Exception e){
- e.printStackTrace();
- }
- }
- public static <K extends Comparable,V extends Comparable> Map<K,V> sortByKeys(Map<K,V> map){
- List<K> keys = new LinkedList<K>(map.keySet());
- Collections.sort(keys);
- //LinkedHashMap will keep the keys in the order they are inserted
- //which is currently sorted on natural ordering
- Map<K,V> sortedMap = new LinkedHashMap<K,V>();
- for(K key: keys){
- sortedMap.put(key, map.get(key));
- }
- return sortedMap;
- //http://javarevisited.blogspot.com/2012/12/how-to-sort-hashmap-java-by-key-and-value.html
- }
- public static <K extends Comparable,V extends Comparable> Map<K,V> sortByValues(Map<K,V> map){
- List<Map.Entry<K,V>> entries = new LinkedList<Map.Entry<K,V>>(map.entrySet());
- Collections.sort(entries, new Comparator<Map.Entry<K,V>>() {
- @Override
- public int compare(Entry<K, V> o1, Entry<K, V> o2) {
- return o2.getValue().compareTo(o1.getValue());
- }
- });
- //LinkedHashMap will keep the keys in the order they are inserted
- //which is currently sorted on natural ordering
- Map<K,V> sortedMap = new LinkedHashMap<K,V>();
- for(Map.Entry<K,V> entry: entries){
- sortedMap.put(entry.getKey(), entry.getValue());
- }
- return sortedMap;
- //http://javarevisited.blogspot.com/2012/12/how-to-sort-hashmap-java-by-key-and-value.html
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement