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

}

}

相关推荐
西柚小萌新5 分钟前
【深入浅出PyTorch】--4.PyTorch基础实战
人工智能·pytorch·python
用户8356290780518 分钟前
掌控PDF页面:使用Python轻松实现添加与删除
后端·python
sg_knight18 分钟前
Spring Cloud与RabbitMQ深度集成:从入门到生产级实战
java·spring boot·spring·spring cloud·消息队列·rabbitmq·stream
hsjkdhs21 分钟前
C++之类的继承与派生
开发语言·c++
暴富奥利奥30 分钟前
完成docker方式的ros环境配置
linux·学习·docker·容器
用户37215742613543 分钟前
Python 实现 Excel 文件加密与保护
python
lly20240643 分钟前
HTML 元素:构建网页的基础
开发语言
低调小一1 小时前
LRU缓存科普与实现(Kotlin 与 Swift)
开发语言·缓存·kotlin
爱好学习的青年人1 小时前
一文详解Go语言字符串
开发语言·后端·golang
雨白1 小时前
深入理解协程的运作机制 —— 调度、挂起与性能
android·kotlin