HashSet と HashMap で最大の数を見つけたいと思います。HashSet に [22,6763,32,42,33] という数字があり、現在の HashSet で最大の数字を見つけたいとします..どうすればよいですか? HashMap についても同じことが言えます。あなたがそれを手伝ってくれることを願っています。ありがとうございました。
8 に答える
HashSet
/を使用せざるを得ない場合は、最大値を見つけるために/HashMap
全体をスキャンする必要があります。のようなライブラリ関数は、このように行います。HashSet
HashMap
Collections.max()
最大値の取得が必要O(1)
で、使用されているコレクションのタイプを変更できる場合は、ソートされたセット/マップ (例: TreeSet
/ TreeMap
) を使用します。
このようなもの:
Set<Integer> values = new HashSet<Integer>() {{
add(22);
add(6763);
add(32);
add(42);
add(33);
}};
int maxValue = Integer.MIN_VALUE;
for (int value : values) {
if (value > maxValue) {
maxValue = value;
}
}
この:
Map<String, Integer> values = new HashMap<String, Integer>() {{
put("0", 22);
put("1", 6763);
put("2", 32);
put("3", 42);
put("4", 33);
}};
int maxValue = Integer.MIN_VALUE;
for (int value : values.values()) {
if (value > maxValue) {
maxValue = value;
}
}
これは、あなたが求めていることを行う簡単な方法です:
public String getMapKeyWithHighestValue(HashMap<String, Integer> map) {
String keyWithHighestVal = "";
// getting the maximum value in the Hashmap
int maxValueInMap = (Collections.max(map.values()));
//iterate through the map to get the key that corresponds to the maximum value in the Hashmap
for (Map.Entry<String, Integer> entry : map.entrySet()) { // Iterate through hashmap
if (entry.getValue() == maxValueInMap) {
keyWithHighestVal = entry.getKey(); // this is the key which has the max value
}
}
return keyWithHighestVal;
}
TreeMap の場合、キー/値がランダムに挿入されることがわかっている場合、ツリーは多かれ少なかれバランスが取れています。ツリーは不均衡になり、データが既にソートされた順序で挿入されると、特定の要素をすばやく見つける (または挿入または削除する) 機能が失われます。アンバランス ツリーの場合、n、O(n)、そうでない場合は O(1) に比例して時間がかかります。
Apache Commons Mathの使用を検討してください。ここにAPI ドキュメントがあります。
対象のクラスはSummaryStatisticsです。sで動作しdouble
、オンザフライで最大値、最小値、平均値などを計算します (値を追加すると)。データ値はメモリに格納されないため、このクラスを使用して非常に大きなデータ ストリームの統計を計算できます。