2016-04-05 4 views
0

複数の最大値を持つArrayListから最大値を取得するにはどうすればよいですか?たとえば、ArrrayListにインデックス2、3、および6に格納されているmax = 20が含まれている場合、そのすべての指標をどのように取得しますか?リストから複数の最大値を収集する方法

+0

'int'の代わりに' List 'を返します。 – SomeJavaGuy

+0

ようこそStackOverflowへ、そうする前に、[良い質問をする方法](http://stackoverflow.com/help/how-to-ask)を読んでみてください。これまでに何を試してみたのか、それがうまくいかない理由(エラーメッセージ)を説明する文脈を少し与えて、読者が簡単に理解できるように質問を書式設定することを検討してください。 – Nacho

+2

最初にアイテムを繰り返し処理して最大値を見つけ、次にアイテムを繰り返してインデックスを収集します。ここで、 'list.get(i).equals(max)' –

答えて

0

最大のファインダは、最大の値を格納します。ここでは、最大値に一致するインデックスのリストを維持する必要があります。

2

明白な方法は、項目がmaxに等しいなインデックスを収集し、最初のCollections.max()で最大値を得ることです:

public <T extends Comparable<? super T>> List<Integer> maxIndicies(List<T> input) { 
    if (input.isEmpty()) // avoid exception thrown by Collections.max() if input is empty 
     return Collections.emptyList(); 
    final T max = Collections.max(input); 
    return IntStream.range(0, input.size()) 
       .filter(i -> input.get(i).compareTo(max) == 0) 
       .boxed() 
       .collect(Collectors.toList()); 
} 

また、私は反復が一度だけ実行され、別の解決策を提案したいと思います。反復処理中に、各項目の2つの項目を確認する必要があります。1)現在のmaxより大きい場合は、新しいmaxを設定し、結果リストをリセットします.2)現在のmaxと等しい場合は、インデックスを結果リストに追加します。

public <T extends Comparable<? super T>> List<Integer> maxIndicies(List<T> input) { 
    T max = null; 
    List<Integer> res = new ArrayList<>(); 
    for (int i = 0; i < input.size(); i++) { 
     T item = input.get(i); 
     if (max == null || item.compareTo(max) > 0) { // item > max => reset 
      res.clear(); 
      max = item; 
      res.add(i); 
     } else if (item.compareTo(max) == 0)   // item equals current max 
      res.add(i); 
    } 
    return res; 
} 

これは最大アイテム自体のあなた値を与えることはありませんが、あなたはどの単に、インデックスを返されたことにより、それを得ることができます:あなたが道を次でそれを行うことができます

List<Integer> maxInd = maxIndicies(list); 
maxValue = maxInd.isEmpty() ? null : list.get(maxInd.get(0)); 
0

public void findMaxIndices() { 
    //Your list with numbers 
    List<Integer> list = new ArrayList<Integer>(Arrays.asList(1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8,9)); 

    //Sorted Map which will contain key as numbers and value as list of indices where your 'key' exists in the list 
    SortedMap<Integer, List<Integer>> indexMapping = new TreeMap<Integer, List<Integer>>(); 

    for(int i = 0; i< list.size(); i++) { 
     //Get the number at index i 
     int number = list.get(i); 
     //Check if any index corresponding to 'number' as index has been added to your map 
     List<Integer> mapping = indexMapping.get(number); 
     if(mapping == null) { 
      //instantiate the list if no index has been added yet 
      mapping = new ArrayList<Integer>(); 
      //Key as your 'number' 
      indexMapping.put(number, mapping); 
     } 
     //Add the index of the 'number' to the mapping list, which is mapped by key as 'number' 
     mapping.add(i);   
    } 
    //Last key in sorted map will be your highest number in the list, get the value corresponding to it. Following prints: [8,17] 
    int maxNumber = indexMapping.lastKey(); //Maximum number found 
    System.out.println(indexMapping.get(maxNumber)); //Indices where maximum number exists 

} 

このように、あなたも簡単に、最も低い値を持つインデックスを見つけることができます:

indexMapping.get(indexMapping.firstKey()); 
0

をこれはあなたのプログラミングコースの宿題のように聞こえます。あなたはそれを自分で行うべきですが、とにかくここに解決策があります。

private List<Integer> getAllMaxIndices(List<Integer> aList) { 

    List<Integer> result = new ArrayList<Integer>(); 

    // check argument 
    if (aList == null || aList.isEmpty()) { 
     return result; 
    } 

    // initialize the list with the index of the first element 
    result.add(0); 

    Integer tmpInt; 
    Integer tmpFirstIndexOfMaxInt; 
    Integer tmpMaxInt; 
    for (int i = 0; i < aList.size(); i++) { 

     // save the current integer and the currently maximum integer 
     tmpInt = aList.get(i); 
     tmpFirstIndexOfMaxInt = result.get(0); 
     tmpMaxInt = aList.get(tmpFirstIndexOfMaxInt); 

     // if the current element is greater than the last found 
     if (tmpInt > tmpMaxInt) { 
      // empty the result 
      result.clear(); 

      // start collecting indices again 
      result.add(i); 
     } 
     // if the current element is equal to the last found 
     else if (tmpInt.intValue() == tmpMaxInt.intValue()) { 
      // insert the current index in the result 
      result.add(i); 
     } 
    } 

    return result; 
} 

この機能をテストするコードを書くことにします。

1

ストリームを使用する別のアプローチ。この解決策では、インデックスが表示されない最大回数を知りたいと仮定しています。

public static Map.Entry<Integer, Long> getMaxWithOccurrences(
     List<Integer> list) { 
    return list 
      .stream() 
      .collect(
        Collectors.groupingBy(i -> i, TreeMap::new, 
          Collectors.counting())).lastEntry(); 
} 
1

私はシンプルで使いやすいループを使用したいと思います。

public List<Integer> getMaxIndices(List<Integer> values) { 
    Integer max = Collections.max(values); 

    List<Integer> maxIndices = new ArrayList<>(); 
    for (int i = 0; i < values.size(); i++) { 
     if (values.get(i).equals(max)) { 
      maxIndices.add(Integer.valueOf(i)); 
     } 
    } 
    return maxIndices; 
} 
1

整数maxValue = Collections.max(list);

int numberofMax = Collections.frequency(list、maxValue);

この "numberofMax"は、 "リスト"にある最大値の数を返します。

関連する問題