Java collection summation maximum minimum sample share
- 2020-04-01 02:52:32
- OfStack
package com.happyelements.athene.game.util;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.Collection;
import com.google.common.collect.Lists;
public class MathUtil {
public static <T extends Comparable<T>> T min(T... ts) {
return min(Lists.newArrayList(ts));
}
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;
}
public static <T extends Comparable<T>> T max(T... ts) {
return max(Lists.newArrayList(ts));
}
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;
}
public static Integer sum(Collection<Integer> values) {
checkNotNull(values);
int sum = 0;
for (Integer integer : values) {
checkNotNull(integer);
sum += integer;
}
return sum;
}
public static Integer sum(Integer... ts) {
return sum(Lists.newArrayList(ts));
}
}