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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/KLH_BAHK/article/details/88775289

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

猜你喜欢

转载自blog.csdn.net/KLH_BAHK/article/details/88775289
今日推荐