如何从列表中收集多个最大值

时间:2016-04-05 13:55:29

标签: java list max

如何从最多超过一个的ArrayList获得最大值?例如,如果ArrrayList包含存储在索引2,3和6的max = 20,那么如何获得所有这些指标?

7 个答案:

答案 0 :(得分:2)

显而易见的方法是首先获得Collections.max()的最大值,然后收集项目等于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()); 
}

此外,我还想提出另一种只进行一次迭代的解决方案。在迭代期间,您需要检查每个项目的两件事:1)如果它大于当前max,则设置新的max并重置结果列表,2)如果它等于当前{{ 1}},将其索引添加到结果列表:

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;
}

答案 1 :(得分:1)

使用流的另一种方法。该解决方案假设您想知道最大值出现的频率(而不是索引)。

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

答案 2 :(得分:1)

我使用简单易读的for循环。

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;
}

答案 3 :(得分:1)

整数maxValue = Collections.max(list);

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

这个“numberofMax”将返回“list”具有的最大值。

答案 4 :(得分:0)

通常的max finders只存储最大值,这里你必须维护一个与最大值匹配的索引列表。

答案 5 :(得分: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());

答案 6 :(得分: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;
}

我将留给您编写测试此功能的代码。