1、map排序
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;
/**
*
* @Description: map排序
*
* @author thrillerzw
* @create time 2014-4-17
*/
public class MapTest {
public static void main(String[] args) {
hashMapSort();
}
/**
*
* @Description: hashmap根据值得长度降序排列
* 思路:将hashmap转为list,用Collections.sort 配合 比较器对list排序
* @author thrillerzw
* @create time 2014-4-17
*/
static void hashMapSort() {
Map<String, String> map = new HashMap<String, String>();
map.put("a", "11");
map.put("c", "1");
map.put("b", "111");
//通过ArrayList构造函数把map.entrySet()转换成list
Set<Map.Entry<String, String>> set = map.entrySet();
List<Map.Entry<String, String>> list = new ArrayList<Map.Entry<String, String>>(set);
Collections.sort(list, new Comparator<Map.Entry<String, String>>() {
public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) {
if (o1.getValue().length() >= o2.getValue().length()) {
return -1;
} else {
return 1;
}
//按key排序,字符串compareTo比较 res=1 或者-1 return -res;
/*int res=o1.getKey().compareTo(o2.getKey());
return res; */
}
});
//排序后,使用排好序的list
System.out.println(list);
}
/**
*
* @Description: TreeMap按照key 降序排列。
* @author thrillerzw
* @create time 2014-4-17 上午11:26:47
*/
static void treemapKeySort() {
Map<String, String> map = new TreeMap<String, String>(new Comparator<String>() {
public int compare(String obj1, String obj2) {
//降序排序
return obj2.compareTo(obj1);
}
});
map.put("b", "h");
map.put("a", "i");
map.put("c", "j");
//输出:map={c=j, b=h, a=i}
System.out.println("map="+map);
}
/**
* @Description: treemap按value升序排列
* @author thrillerzw
* @create time 2014-4-17
*/
static void treemapValsort() {
List<Map.Entry<String, String>> mappingList = null;
Map<String, String> map = new TreeMap<String, String>();
map.put("b", "h");
map.put("a", "i");
map.put("c", "j");
//默认按key升序排序 输出:map={a=bread, b=month, c=attack}
System.out.println("map="+map);
//通过ArrayList构造函数把map.entrySet()转换成list
mappingList = new ArrayList<Map.Entry<String, String>>(map.entrySet());
//通过比较器实现比较排序
Collections.sort(mappingList, new Comparator<Map.Entry<String, String>>() {
public int compare(Map.Entry<String, String> mapping1, Map.Entry<String, String> mapping2) {
return mapping1.getValue().compareTo(mapping2.getValue());
}
});
// 输出:mappingList=[b=h, a=i, c=j]
System.out.println("mappingList="+mappingList);
}
}
2、集合转换
//数组转为List
List<String> dataList = Arrays.asList(valArr);
//list转为set
Set<String> tryServers = new HashSet<String>(Arrays.asList(servers));