hashmap排序

一、按key进行排序
package com.jack.veloctiy.utils;

import java.util.Arrays;
import java.util.HashMap;

/**
*
*/
public class SortByKeyOfMap {

public static void main(String[] args) {

@SuppressWarnings("serial")
HashMap<String, String> datas = new HashMap<String, String>() {

{
put("a", "Winter Lau");
put("b", "Yier");
put("c", "Nothing");
put("d", "Zolo");
}
};
Object[] key = datas.keySet().toArray();
Arrays.sort(key);
for (int i = 0; i < key.length; i++) {
System.out.println(datas.get(key[i]));
}
}
}
 二、按value进行排序
package com.jack.veloctiy.utils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.TreeMap;

/**
*
*/
public class SortByValueOfMap {

public static void main(String[] args) {

@SuppressWarnings("serial")
HashMap<String, String> datas = new HashMap<String, String>() {

{
put("Winter Lau", "a");
put("Yier", "b");
put("Nothing", "c");
put("Zolo", "d");
}
};

ByValueComparator bvc = new ByValueComparator(datas);

// 第一种方法
TreeMap<String, String> sorted_map = new TreeMap<String, String>(bvc);
sorted_map.putAll(datas);

for (String name : sorted_map.keySet()) {
System.out.printf("%s -> %s\n", name, datas.get(name));
}

// 第二种方法
List<String> keys = new ArrayList<String>(datas.keySet());
Collections.sort(keys, bvc);
for (String key : keys) {
System.out.printf("%s -> %s\n", key, datas.get(key));
}
}

/**
* 比较器,按照value的自然顺序升序排列
*
* @author Administrator
*/
static class ByValueComparator implements Comparator<String> {

HashMap<String, String> base_map;

public ByValueComparator(HashMap<String, String> base_map) {
this.base_map = base_map;
}

public int compare(String arg0, String arg1) {
if (!base_map.containsKey(arg0) || !base_map.containsKey(arg1)) {
return 0;
}

if (base_map.get(arg0).compareToIgnoreCase(base_map.get(arg1)) > 0) {
return 1;
} else if (base_map.get(arg0).compareToIgnoreCase(base_map.get(arg1)) == 0) {
return 0;
} else {
return -1;
}
}
}
}

你可能感兴趣的:(HashMap)