com.datastax.util.collection.CollectionUtil Maven / Gradle / Ivy
The newest version!
package com.datastax.util.collection;
import com.datastax.collection.KeyValue;
import java.util.*;
/**
* UserItem: Anders Hong
* Date: 10/9/13
* Time: 10:40 AM
*/
public class CollectionUtil {
public static List> countListKV(List list){
List> kvList=new ArrayList<>();
Map map=countList(list);
for(String key : map.keySet()){
kvList.add(new KeyValue<>(key, map.get(key).longValue()));
}
return kvList;
}
public static Map countList(List list){
Map map=new HashMap();
for(String value : list){
if(map.containsKey(value)){
int count=map.get(value);
count++;
map.remove(value);
map.put(value,count);
}else {
map.put(value,1);
}
}
return map;
}
public static Map countListPercent(List list){
Map map=countList(list);
return countMapPercent(map);
}
public static Map countMapPercent(Map map){
Map perMap=new HashMap();
double total=0;
for(String key : map.keySet()){
int weight=map.get(key);
total+=weight;
}
for(String key : map.keySet()){
double weight=map.get(key);
perMap.put(key,weight * 100 / total);
}
return perMap;
}
/**
* map 按照value排序
*
* @return
*/
public static List> sortMapByValue(Map map, final int sort) {
List> orderList = new ArrayList>(map.entrySet());
Collections.sort(orderList, new Comparator>() {
@Override
@SuppressWarnings("unchecked")
public int compare(Map.Entry o1, Map.Entry o2) {
return (((Comparable) o2.getValue()).compareTo(o1.getValue())) * sort;
}
});
return orderList;
}
public static Map