Java当中使用TreeMap进行WordCount并且排序

注:JDK要使用1.8以上的

package com.lyl.it;

import static com.lyl.it.Common.getValueComparator;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public class TestTreeMap {
    
	public static void main(String[] args) {
		List list = new ArrayList<>();
		list.add("aa");
		list.add("vv");
		list.add("bb");
		list.add("nn");
		list.add("cc");
		list.add("mm");
		list.add("aa");
		list.add("nn");
		list.add("aa");
		list.add("aa");
		list.add("aa");
		list.add("nn");
		
     TreeMap couter = new TreeMap();
    
     for (int i = 0; i < list.size(); i++) {
 		String word =list.get(i);
 		int count = couter.getOrDefault(word,0) + 1;
 		couter.put(word, count);
 	 }
     
     List> listCounter = new ArrayList>(couter.entrySet());
     Collections.sort(listCounter,getValueComparator());
     
     for (int i = 0; i < listCounter.size(); i++) {
 		System.out.println(listCounter.get(i));
 	 }
		
   }
}
package com.lyl.it;

import java.util.Comparator;
import java.util.Map;

public class Common {

    public static  Comparator>  getValueComparator(){
        // 降低序比较器
        Comparator> valueComparator = new Comparator>() {
            @Override
            public int compare(Map.Entry o1,Map.Entry o2) {
               
                return o2.getValue() - o1.getValue();
            }
        };
        return valueComparator;
    }
    
    
}

运行的结果如下:

aa=5
nn=3
bb=1
cc=1
mm=1
vv=1

 

你可能感兴趣的:(JAVA,TreeMap,排序)