2012-09-18 50 views
0

下圖包含字符串鍵和Sting值。值是用逗號分隔的字符串。 Map如何通過此String的第四個元素進行排序?按csv排序映射字符串值

所以這個地圖:

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 

這可能使用地圖嗎?

+1

這可能是有趣的:http://stackoverflow.com/questions/109383/how-to-sort-a-mapkey-value-on-the-values-in-java –

回答

0

你可以做到這一點實現比較如下:

要小心了「帽子戲法」的標籤,在這裏我解釋一下「絕招」

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