Collections工具獲取最大值和最小值


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

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM