Java コレクションを使用している場合、特にジェネリックを使用してユーティリティ メソッドを記述している場合、私のコードは見苦しく肥大化しており、null チェック、ネストされたループ、および繰り返しでいっぱいです。この一例を中心に、改善案をお願いします。
EnumMap
値が評価のリストである があるとします。たとえば、enum
自体が果物を表し、各値がさまざまな人によって付けられたリストの評価を表しているとします。
APPLE -> [1, 3, 4]
ORANGE -> [2, 0, 5]
John rated apple 1, Mary rated apple 3, Steve rated apple 4
John rated orange 2, Mary rated orange 0, Steve rated orange 5
Note the specific names are irrelevant and provided only to clarify the setup
ここで、上記のようなデータ構造を受け取り、各人の好きな果物のリストを返すユーティリティ メソッドを書きたいと思います。したがって、上記のサンプル データの期待される結果は次のようになり[ORANGE, APPLE, ORANGE
ます。2 > 1
3 > 0
5 > 4
以下は、これを行うための現在の方法です。同じアルゴリズムを書くための同等の (またはそれ以上の) 効率的で、よりクリーンな方法が必要です。
ありがとう!
public class MyListUtil {
public static <K extends Enum<K>, T extends Object & Comparable<? super T>> List<K> maxKeysByIndex(EnumMap<K, List<T>> enumMap) {
Iterator<K> keysIter = enumMap.keySet().iterator();
int sizeOfAllLists = enumMap.get(keysIter.next()).size();
List<K> ret = new ArrayList<K>();
for (int i=0; i<sizeOfAllLists; i++) {
keysIter = enumMap.keySet().iterator();
K maxIndexKey = null;
T maxIndexVal = null;
while (keysIter.hasNext()){
K curKey = keysIter.next();
T curVal = enumMap.get(curKey).get(i);
if (maxIndexVal == null || curVal.compareTo(maxIndexVal) > 0) {
maxIndexVal = curVal;
maxIndexKey = curKey;
}
}
ret.add(maxIndexKey);
}
return ret;
}
}