獲取List集合中的最大值和最小值

調用Collections類中的方法

最大值:

public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll) {
  Iterator<? extends T> i = coll.iterator();
  T candidate = i.next();

  while (i.hasNext()) {
    T next = i.next();
    if (next.compareTo(candidate) > 0)
      candidate = next;
  }
  return candidate;
}

最小值:

public static <T extends Object & Comparable<? super T>> T min(Collection<? extends T> coll) {
  Iterator<? extends T> i = coll.iterator();
  T candidate = i.next();

  while (i.hasNext()) {
    T next = i.next();
    if (next.compareTo(candidate) < 0)
      candidate = next;
  }
  return candidate;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章