? asked in 電腦與網際網路程式設計 · 10 years ago

hashmap,Set 排序問題

是這樣的, 我用一個hashmap加入了數筆資料, 再用TreeMap去進行排序,

結果如下:

-------------------------------------------------

101==>50

354==>154

510==>54

854==>9530

A101==>4190

A201==>346

C125==>100

F905==>1320

-------------------------------------------------

現在我想排成這樣子, 原理是先排英文再排數字的,

希望的結果如下:

-------------------------------------------------

A101==>4190

A201==>346

C125==>100

F905==>1320

101==>50

354==>154

510==>54

854==>9530

-------------------------------------------------

請問有大大會嗎@@" 感謝!

程式如下:

-------------------------------------------------

import java.io.*;

import java.util.Set;

import java.util.HashMap;

import java.util.TreeMap;

import java.util.Collections;

public class W20110424 {

public static void main(String[] args) {

HashMap_Sample01();

}

public static void HashMap_Sample01(){

HashMap<String,Integer> hm=new HashMap<String,Integer>();

hm.put("C125", 100);

hm.put("A101", 4190);

hm.put("A201", 346);

hm.put("F905", 1320);

hm.put("101", 50);

hm.put("510", 54);

hm.put("354", 154);

hm.put("854", 9530);

Set<String> set1 = hm.keySet();

TreeMap Sorthm = new TreeMap();

Sorthm.putAll(hm);

Set<String> set2 = Sorthm.keySet();

for (String key : set2) {

System.out.println(key + "==>" + hm.get(key));

}

}

}

1 Answer

Rating
  • 10 years ago
    Favorite Answer

    基本上是利用TreeMap方法是辦不到你的特殊需求

    因為排序是根據位元碼在做排序的,請見ASCII表

    要麼是0123456789 ABCD...(升序)

    要麼是...DCBA9876543210 (降序)如下程式碼修改

    將TreeMap Sorthm = new TreeMap();

    改TreeMap Sorthm = new TreeMap(Collections.reverseOrder());

    所以要達到您的需求,只能在foreach裡面再做處理了

    2011-04-25 10:33:18 補充:

    除非你改成兩個hashmap一個存數字KET,一個字母KEY

    做各自排序各自輸出...不過沒什麼意義就是

    Source(s): Me, Me
Still have questions? Get your answers by asking now.