[Java][Cellection和Map获取最大和最小值以及它们的位置]

1.对于Collection的数据,可以使用Collections工具获取最大值和最小值。最大值和最小值的下标可以通过List的indexOf方法获取。
2.对于Map的数据,可以先将Map的value转成Collection,然后通过Collections工具获取最大值和最小值。至于最大值和最小值的下标只能通过遍历来获取。

private void getMaxAndMin()
{
    List<Integer> list = new ArrayList<>();
    list.add(1);
    list.add(2);
    list.add(3);
    list.add(4);
    list.add(5);
    Integer listMax = Collections.max(list);
    Integer listMin = Collections.min(list);
    Log.i("getMaxAndMin","listMax:"+listMax+" listMin:"+listMin);
    Log.i("getMaxAndMin","listMax index:"+list.indexOf(listMax)+" listMin index:"+list.indexOf(listMin));
    Map<Integer,Integer> map = new HashMap<>();
    map.put(0,1);
    map.put(1,2);
    map.put(2,3);
    map.put(3,4);
    map.put(4,5);

    Collection<Integer> collection = map.values();
    Integer mapMax = Collections.max(collection);
    Integer mapMin = Collections.min(collection);
    Log.i("getMaxAndMin","mapMax:"+mapMax+" mapMin:"+mapMin);

    Integer mapMaxIndex = null;
    Integer mapMinIndex = null;
    Set set = map.entrySet();
    Iterator iterator = set.iterator();
    while (iterator.hasNext())
    {
        Map.Entry entry = (Map.Entry) iterator.next();
        if (entry.getValue().equals(mapMax)) {
            mapMaxIndex = (Integer) entry.getKey();
        }
        if (entry.getValue().equals(mapMin)) {
            mapMinIndex = (Integer) entry.getKey();
        }
    }
    Log.i("getMaxAndMin","mapMaxIndex:"+mapMaxIndex+" mapMinIndex:"+mapMinIndex);
}

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容