java集合求和最大值最小值示例分享

2022-10-20,,,,

复制代码 代码如下:
package com.happyelements.athene.game.util;

import static com.google.common.base.preconditions.checknotnull;

import java.util.collection;

import com.google.common.collect.lists;

/**
 * math工具类
 * 
 * @version 1.0
 * @since 1.0
 */
public class mathutil {

 /**
  * @see mathutil#min(collection)
  * @param ts
  * @return
  */
 public static <t extends comparable<t>> t min(t... ts) {
  return min(lists.newarraylist(ts));
 }

 /**
  * 取最小值
  * @param values
  * @throws nullpointerexception if (values == null || values.contain(null))
  * @return
  */
 public static <t extends comparable<t>> t min(collection<t> values) {
  checknotnull(values);
  t min = null;

  for (t t : values) {
   checknotnull(t);
   if (min == null) {
    min = t;
   } else {
    min = min.compareto(t) < 0 ? min : t;
   }
  }
  return min;
 }

 /**
  * @see mathutil#max(collection)
  * @param ts
  * @return
  */
 public static <t extends comparable<t>> t max(t... ts) {
  return max(lists.newarraylist(ts));
 }

 /**
  * 取最大值
  * @param values
  * @throws nullpointerexception if (values == null || values.contain(null))
  * @return
  */
 public static <t extends comparable<t>> t max(collection<t> values) {
  checknotnull(values);
  t max = null;

  for (t t : values) {
   checknotnull(t);
   if (max == null) {
    max = t;
   } else {
    max = max.compareto(t) > 0 ? max : t;
   }
  }
  return max;
 }

 /**
  * 求和
  * @param values
  * @throws nullpointerexception if (values == null || values.contain(null))
  * @return
  */
 public static integer sum(collection<integer> values) {
  checknotnull(values);
  int sum = 0;
  for (integer integer : values) {
   checknotnull(integer);
   sum += integer;
  }
  return sum;
 }

 /**
  * @see mathutil#sum(collection)
  * @param ts
  * @return
  */
 public static integer sum(integer... ts) {
  return sum(lists.newarraylist(ts));
 }

}

《java集合求和最大值最小值示例分享.doc》

下载本文的Word格式文档,以方便收藏与打印。