7

私は次のものを持っていますHashMap

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

値に従って注文する最も簡単な方法は何ですか?

4

4 に答える 4

9

値でa をソートすることはできませんMap。特に、まったくソートできない a はソートHashMapできません。

代わりに、エントリを並べ替えることができます。

List<Map.Entry<String, Integer>> entries = new ArrayList<Map.Entry<String, Integer>>(map.entrySet());
Collections.sort(entries, new Comparator<Map.Entry<String, Integer>>() {
  public int compare(
      Map.Entry<String, Integer> entry1, Map.Entry<String, Integer> entry2) {
    return entry1.getValue().compareTo(entry2.getValue());
  }
});

カウントの昇順でエントリをソートします。

于 2012-10-16T16:57:47.717 に答える
4

を使用して、マップから一連のエントリ (Setの) を取得できます。それらを反復処理し、 で値を確認してください。Map.Entrymap.entrySet()getValue()

于 2012-10-16T16:55:12.820 に答える
1

順番に印刷したい場合の回避策(保存しない)。

  1. 新しいマップ ( tempMap) を作成し、値をキーとして、キーを値として配置します。キーを一意にするには、キーのそれぞれに一意の値を追加してください (例: key1 = value1+@0)。

  2. 値のリストをリストとして取得しmap.values()ますmyVlues

  3. myVluesリストを次のように並べ替えますCollections.sort(myVlues)

  4. 次に、 を繰り返し、からmyVlues対応するものを取得し、key.substring(0, key.length-2) などのキーを復元し、キーと値のペアを出力します。keytempMap

お役に立てれば。

于 2012-10-16T17:04:34.610 に答える
1

TreeMapは、 Comparatorによって定義された順序でエントリを保持できます

  1. 最大値を最初に配置することで Map を並べ替えるコンパレーターを作成できます。
  2. 次に、その Comparator を使用する TreeMap を構築します。
  3. 次に、マップ内のすべてのエントリをcountsComparator に入れます。
  4. 最後に、マップ内の最初のキーを取得します。これは、最も一般的な単語 (複数の単語の数が等しい場合は、少なくとも 1 つ) である必要があります。

    public class Testing {
        public static void main(String[] args) {
    
            HashMap<String,Double> counts = new HashMap<String,Integer>();
    
            // Sample word counts
            counts.put("the", 100);
            counts.put("pineapple",5);
            counts.put("a", 50);
    
            // Step 1: Create a Comparator that order by value with greatest value first
            MostCommonValueFirst mostCommonValueFirst =  new MostCommonValueFirst(counts);
    
            // Step 2: Build a TreeMap that uses that Comparator
            TreeMap<String,Double> sortedMap = new TreeMap<String,Integer (mostCommonValueFirst);
    
            // Step 3: Populate TreeMap with values from the counts map
            sortedMap.putAll(counts);
    
            // Step 4: The first key in the map is the most commonly used word
            System.out.println("Most common word: " + sortedMap.firstKey());
        }
    }
    
    private class MostCommonValueFirst implements Comparator<String> {
       Map<String, Integer> base;
    
       public MostCommonValueFirst(Map<String, Integer> base) {
          this.base = base;
       }
    
       // Note: this comparator imposes orderings that are inconsistent with equals.    
       public int compare(String a, String b) {
          if (base.get(a) >= base.get(b)) {
              return 1;
          } else {
             return -1;
          } // returning 0 would merge keys
       }
     }
    

ソース: https://stackoverflow.com/a/1283722/284685

于 2012-10-16T17:07:32.347 に答える