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

}

}

相关推荐
10岁的博客12 分钟前
PyTorch快速搭建CV模型实战
人工智能·pytorch·python
老华带你飞12 分钟前
商城推荐系统|基于SprinBoot+vue的商城推荐系统(源码+数据库+文档)
java·前端·数据库·vue.js·spring boot·毕设·商城推荐系统
花北城15 分钟前
【C#】List快速检查重复数据
开发语言·c#
一 乐16 分钟前
物业管理系统|小区物业管理|基于SprinBoot+vue的小区物业管理系统(源码+数据库+文档)
java·前端·数据库·vue.js·spring boot·后端
蛮三刀酱27 分钟前
复杂度的代价远比你想象得大
java·架构
这周也會开心32 分钟前
Spring框架
java·数据库·spring
yolo_Yang35 分钟前
【Spring Boot】Spring Boot解决循环依赖
java·spring boot·后端
寒秋丶37 分钟前
AutoGen多智能体协作、人机交互与终止条件
人工智能·python·microsoft·ai·人机交互·ai编程·ai写作
练习时长一年1 小时前
Jdk反射优化
java·开发语言
Turnsole_y1 小时前
pytest与Selenium结合使用指南
开发语言·python