按csv字符串值排序映射

时间:2012-09-18 11:11:56

标签: java

下面的地图包含字符串键和Sting值。值是逗号分隔的String。 如何根据此String的第四个元素对Map进行排序?

所以这张地图:

key1    a,b,c,1
key2    a,b,c,4
key3    a,b,c,3
key4    a,b,c,2

成为:

key2    a,b,c,4
key3    a,b,c,3
key4    a,b,c,2
key1    a,b,c,1

这可以使用Map吗?

1 个答案:

答案 0 :(得分:0)

您可以按如下方式实现比较器:

小心“TRICK”标签,在那里我解释“技巧”

import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class SortedMap{

public static void main(String[] args) {

    Map<String,String> inputMap = new HashMap<String,String>();
    inputMap.put("key1", "a,b,c,1");
    inputMap.put("key2", "a,b,c,4");
    inputMap.put("key3", "a,b,c,3");
    inputMap.put("key4", "a,b,c,2");

    // raw input
    System.out.println("Input");
    for (Map.Entry entry : inputMap.entrySet()) {
        System.out.println("Key: "+entry.getKey()+", value: "+entry.getValue());
    }

    Map<String,String> sortedMap = mySort(inputMap);

    System.out.println("Output");
    for (Map.Entry entry : sortedMap.entrySet()) {
        System.out.println("Key: "+entry.getKey()+", value: "+entry.getValue());
    }
}

private static Map mySort(Map inputMap) {
    // to list
    List list = new LinkedList(inputMap.entrySet());

    Collections.sort(list, new Comparator() {
            public int compare(Object o1, Object o2) {
            String v1 = (String)((Map.Entry) (o1)).getValue();
            // split by ,
            String[] v1Split = v1.split(",");
            // get last value
            String v1Value = v1Split[v1Split.length-1];

            // compact syntax
            String v2Value = (((String)((Map.Entry) (o2)).getValue()).split(","))[3];

            // TRICK: -1 for reverse
            return v1Value.compareTo(v2Value) * -1;
            }
            });

    // TRICK: to LinkedMap
    Map sortedMap = new LinkedHashMap();
    for (Iterator it = list.iterator(); it.hasNext();) {
        Map.Entry entry = (Map.Entry)it.next();
        sortedMap.put(entry.getKey(), entry.getValue());
    }
    return sortedMap;
}   
}

跑完后,我得到了这个输出:

Input
Key: key4, value: a,b,c,2
Key: key3, value: a,b,c,3
Key: key2, value: a,b,c,4
Key: key1, value: a,b,c,1
Output
Key: key2, value: a,b,c,4
Key: key3, value: a,b,c,3
Key: key4, value: a,b,c,2
Key: key1, value: a,b,c,1