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

}

}

相关推荐
梦想不只是梦与想8 小时前
Python 属性访问的 MRO 规则
python·mro规则
Ulyanov8 小时前
基于 Python 的三维动态导弹攻防演示系统设计与实现:从架构到实战的深度剖析
开发语言·python·qt·架构·雷达电子对抗
小雅痞8 小时前
[Java][Leetcode middle] 15. 三数之和
java·算法·leetcode
苍煜8 小时前
Java自定义注解-SpringBoot实战
java·开发语言·spring boot
Leinwin8 小时前
Claude 四月宕机七次:从一次事故看企业级 AI 部署的容灾设计
后端·python·flask
棉猴8 小时前
Python海龟绘图之绘制文本
javascript·python·html·write·turtle·海龟绘图·输出文本
XS0301068 小时前
Java ArrayList
java·开发语言
渣渣盟8 小时前
大数据技术栈全景图:从零到一的入门路线(深度实战版)
大数据·hadoop·python·flink·spark
凯尔萨厮8 小时前
Springboot2.x+JSP项目创建
java·数据库
暴力求解8 小时前
Linux---保存信号
linux·运维·服务器·开发语言·操作系统