guava ListInteger 汇总
要对一个Guava List
import com.google.common.collect.Lists;
import com.google.common.collect.Streams;
import java.util.List;
public class GuavaListSummarizeExample {
public static void main(String[] args) {
List<Integer> numbers = Lists.newArrayList(1, 2, 3, 4, 5);
// 汇总整数列表中的所有元素
int sum = Streams.stream(numbers)
.mapToInt(Integer::intValue)
.sum();
System.out.println("Sum: " + sum);
// 计算整数列表中的最大值
int max = Streams.stream(numbers)
.mapToInt(Integer::intValue)
.max()
.orElse(0);
System.out.println("Max: " + max);
// 计算整数列表中的最小值
int min = Streams.stream(numbers)
.mapToInt(Integer::intValue)
.min()
.orElse(0);
System.out.println("Min: " + min);
// 计算整数列表中的平均值
double average = Streams.stream(numbers)
.mapToInt(Integer::intValue)
.average()
.orElse(0.0);
System.out.println("Average: " + average);
}
}
在这个示例中,我们使用Guava的Lists类创建了一个包含整数的列表。然后,我们使用Streams.stream()方法将列表转换为一个流,并使用mapToInt()方法将流中的元素映射为整数。接下来,我们可以使用sum()方法对整数进行求和,使用max()方法找到最大值,使用min()方法找到最小值,使用average()方法计算平均值。
请注意,我们使用orElse()方法来处理可能不存在的最大值、最小值和平均值。如果列表为空,这些方法将返回一个默认值(在示例中为0)
原文地址: https://www.cveoy.top/t/topic/ivHu 著作权归作者所有。请勿转载和采集!