2014-09-04 7 views
5

के साथ अवरोही क्रम में मानचित्र मान छंटनी मेरे पास Map<String,Integer> है जिनकी प्रविष्टियों (कुंजी) को अवरोही मूल्य के क्रम में सॉर्ट करने की आवश्यकता है। उदाहरण के लिए, मानचित्र लग रहा है, तो जैसे:ग्रोवी

"a" => 5 
"b" => 3 
"c" => 12 
"d" => 9 

छँटाई के बाद यह की तरह लग रहे करने की जरूरत है:

"c" => 12 
"d" => 9 
"a" => 5 
"b" => 3 

मेरे सबसे अच्छे प्रयास अब तक:

def test() { 
    Map<String,Integer> toSort = new HashMap<String,Integer>() 
    toSort.put("a", 5) 
    toSort.put("b", 3) 
    toSort.put("c", 12) 
    toSort.put("d", 9) 

    Map<String,Integer> sorted = sortMapDesc(toSort) 
    sorted.each { 
     println "${it.key} has a value of ${it.value}." 
    } 
} 

def sortMapDesc(Map<String,Integer> toSort) { 
    println "Sorting..." 
    println toSort 

    // The map of properly sorted entries. 
    Map<String,Integer> sorted = new HashMap<String,Integer>() 

    // Keep scanning the map for the key with the highest value. When we find 
    // it, add it as the next entry to the 'sorted' map, and then zero it out 
    // so it won't show up as the highest on subsequent scans/passes. Stop scanning 
    // when the entire 'toSort' map contains keys with zeros. 
    while(!mapIsAllZeros(toSort)) { 
     int highest = -1 
     String highestKey = "" 
     toSort.each { 
      if(it.value > highest) { 
       highest = it.value 
       highestKey = it.key 
      } 
     } 

     toSort.put(highestKey, 0) 
     sorted.put(highestKey, highest) 
    } 

    sorted 
} 

def mapIsAllZeros(Map<String,Integer> toCheck) { 
    toCheck.values().every{!it} 
} 

जब मैं चलाने test() मैं निम्नलिखित आउटपुट प्राप्त करें:

Sorting... 
[d:9, b:3, c:12, a:5] 
d has a value of 9. 
b has a value of 3. 
c has a value of 12. 
a has a value of 5. 

मैं यहाँ गलत कहां जा रहा हूं?

+0

तुम्हारा मतलब मूल्यों को सॉर्ट? प्रश्न में चाबियाँ नहीं हैं? –

उत्तर

12

बस कार्य करें:

​def m = [a:​5, b:12, c:3, d:9] 
def sorted = m.sort { a, b -> b.value <=> a.value } 
+9

एक और विकल्प सिर्फ है: 'm.sort {-it.value}' – Steinar

+0

@tim_yates hi, क्या आप यह समझा सकते हैं कि यह बंद करने का अर्थ क्या है, बी -> बी .value <=> a.value .. धन्यवाद :) – user3714598

+0

@ user3714598, '<=>' "स्पेसशिप ऑपरेटर" है। यह 'तुलना करने की विधि' के लिए प्रतिनिधि है। प्रलेखन के लिए [यहां] (http://docs.groovy-lang.org/latest/html/documentation/index.html#_spaceship_operator) देखें। – AutonomousApps

1

छंटाई करने के लिए, टिम कार्यान्वयन जाने का रास्ता है। लेकिन अगर आप सोच रहे हैं कि आपका उदाहरण कोड आपके काम के अनुसार क्यों काम नहीं करता है, तो जवाब यह है कि परिवर्तनीय 'सॉर्टेड' को केवल हैश मैप के बजाय लिंक्ड हैशैप टाइप करने की आवश्यकता है। आप इसे स्पष्ट रूप से सेट कर सकते हैं:

Map<String,Integer> sorted = new LinkedHashMap<String,Integer>() 

या, बस ऐसा करते हैं:

Map<String,Integer> sorted = [:]