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));

}

}

相关推荐
lee_curry几秒前
AI Agent 工程师完整学习路线(面向生产级项目与面试)
人工智能·学习·ai·面试·agent
小毛驴8505 分钟前
前端开发学习路线可以分为几个层次
学习
菜鸡66666 分钟前
绕过cf验证,部署 FlareSolverr 服务使用request处理
python·cloudflare
血小板要健康7 分钟前
链表 阶段算法总结
java·数据结构·笔记·算法·leetcode·链表
坐吃山猪7 分钟前
【多线程】CompletableFuture使用
java·开发语言·多线程
star learning white13 分钟前
STM32入门学习3
stm32·单片机·学习
浔溺14 分钟前
al+大数据每日学习笔记31
大数据·笔记·学习
!!!!81315 分钟前
AI Coding学习
学习
山岚的运维笔记21 分钟前
mysql 专业笔记 -- 第 8 章:使用变量
运维·数据库·笔记·后端·学习·mysql·dba
CHPCWWHSU23 分钟前
DeepSeek-Harness-Qt将浏览器端Agent装入桌面应用
开发语言·qt