私は次のものを持っていますHashMap
:
HashMap<String, Integer> counts = new HashMap<String, Integer>();
値に従って注文する最も簡単な方法は何ですか?
私は次のものを持っていますHashMap
:
HashMap<String, Integer> counts = new HashMap<String, Integer>();
値に従って注文する最も簡単な方法は何ですか?
値で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());
}
});
カウントの昇順でエントリをソートします。
を使用して、マップから一連のエントリ (Set
の) を取得できます。それらを反復処理し、 で値を確認してください。Map.Entry
map.entrySet()
getValue()
順番に印刷したい場合の回避策(保存しない)。
新しいマップ ( tempMap
) を作成し、値をキーとして、キーを値として配置します。キーを一意にするには、キーのそれぞれに一意の値を追加してください (例: key1 = value1+@0)。
値のリストをリストとして取得しmap.values()
ますmyVlues
myVlues
リストを次のように並べ替えますCollections.sort(myVlues)
次に、 を繰り返し、からmyVlues
対応するものを取得し、key.substring(0, key.length-2) などのキーを復元し、キーと値のペアを出力します。key
tempMap
お役に立てれば。
TreeMapは、 Comparatorによって定義された順序でエントリを保持できます。
counts
Comparator に入れます。最後に、マップ内の最初のキーを取得します。これは、最も一般的な単語 (複数の単語の数が等しい場合は、少なくとも 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
}
}