Java学习,查找List最大最小值

Java可以通过,多种方式查找List中最大值和最小值。最直接的方法,使用Stream API,它提供了简洁且强大的方法来处理集合。

使用Stream API查找:

import java.util.Collections;

import java.util.List;

import java.util.Optional;

public class ListMinMaxExample {

public static void main (String[] args) {

List<Integer> numbers = new ArrayList<>();

// 初始化列表

Collections.addAll(numbers, 3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5);

// 查找最大值

Optional<Integer> max = numbers.stream().max(Integer::compare);

// 查找最小值

Optional<Integer> min = numbers.stream().min(Integer::compare);

// 输出结果

if (max.isPresent()) {

System.out.println("最大值: " + max.get());

} else {

System.out.println("列表为空,无法找到最大值");

}

if (min.isPresent()) {

System.out.println("最小值: " + min.get());

} else {

System.out.println("列表为空,无法找到最小值");

}

}

}

使用Collections类max() 和 min()查找:

import java.util.*;

public class Main {

public static void main (String[] args) {

List list = Arrays.asList("one Two three Four five six one three Four".split(" "));

System.out.println(list);

System.out.println("最大值: " + Collections.max(list));

System.out.println("最小值: " + Collections.min(list));

}

}

相关推荐
Lei活在当下3 小时前
【Perfetto从入门到精通】4.使用 heapprofd 工具采样追踪 Java/Native 内存分配
android·性能优化·架构
陈天伟教授3 小时前
人工智能训练师认证教程(2)Python os入门教程
前端·数据库·python
陈文锦丫3 小时前
MQ的学习
java·开发语言
乌暮3 小时前
JavaEE初阶---线程安全问题
java·java-ee
2301_764441333 小时前
Aella Science Dataset Explorer 部署教程笔记
笔记·python·全文检索
爱笑的眼睛113 小时前
GraphQL:从数据查询到应用架构的范式演进
java·人工智能·python·ai
BoBoZz193 小时前
ExtractSelection 选择和提取数据集中的特定点,以及如何反转该选择
python·vtk·图形渲染·图形处理
liwulin05063 小时前
【PYTHON-YOLOV8N】如何自定义数据集
开发语言·python·yolo
Bathwind-w4 小时前
FOC开发工具学习
学习
alexhilton4 小时前
学会在Jetpack Compose中加载Lottie动画资源
android·kotlin·android jetpack