List<BigDecimal> sydfList = new ArrayList<>(); 找到集合中的最大值和最小值

To find the maximum and minimum values in the sydfList which contains BigDecimal objects, you can use Java 8 streams for a concise and efficient solution. Here's how you can do it:

java 复制代码
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<BigDecimal> sydfList = new ArrayList<>();
        sydfList.add(new BigDecimal("10.5"));
        sydfList.add(new BigDecimal("8.2"));
        sydfList.add(new BigDecimal("15.7"));
        sydfList.add(new BigDecimal("6.4"));
        
        // Finding the maximum value
        BigDecimal max = sydfList.stream()
                                 .max(BigDecimal::compareTo)
                                 .orElse(BigDecimal.ZERO);
        
        // Finding the minimum value
        BigDecimal min = sydfList.stream()
                                 .min(BigDecimal::compareTo)
                                 .orElse(BigDecimal.ZERO);
        
        System.out.println("Maximum value: " + max);
        System.out.println("Minimum value: " + min);
    }
}

Explanation:

  1. Initialization : We initialize sydfList with BigDecimal objects.

  2. Finding Maximum Value:

    • We use stream() on sydfList to convert it into a stream of BigDecimal.
    • max() function is applied on the stream to find the maximum value.
    • BigDecimal::compareTo is used as the comparator to determine the ordering of BigDecimal objects.
    • orElse(BigDecimal.ZERO) ensures that if the stream is empty, we default to BigDecimal.ZERO.
  3. Finding Minimum Value:

    • Similarly, min() function is used to find the minimum value.
    • Again, BigDecimal::compareTo is used as the comparator.
    • orElse(BigDecimal.ZERO) handles the case where the stream is empty.
  4. Output: Finally, we print out the maximum and minimum values found in the list.

This approach leverages Java 8's Stream API, which provides a functional approach to operate on collections, making the code concise and readable.

相关推荐
.YM.Z8 分钟前
【数据结构】:排序(一)
数据结构·算法·排序算法
q***925133 分钟前
Windows上安装Go并配置环境变量(图文步骤)
开发语言·windows·golang
凭栏落花侧2 小时前
打印机脱机状态应该怎么处理
windows
q***57743 小时前
MySQL 实验1:Windows 环境下 MySQL5.5 安装与配置
windows·mysql·adb
sin_hielo4 小时前
leetcode 2435
数据结构·算法·leetcode
q***31834 小时前
Windows安装Rust环境(详细教程)
开发语言·windows·rust
crescent_悦4 小时前
PTA L1-020 帅到没朋友 C++
数据结构·c++·算法
q***82916 小时前
windows同时安装两个不同版本的Mysql
windows·mysql·adb
稚辉君.MCA_P8_Java6 小时前
Gemini永久会员 Java动态规划
java·数据结构·leetcode·排序算法·动态规划
dntktop7 小时前
搜索+计算+插件…这个“全能管家”让你告别80%的桌面图标
运维·windows·自动化·编辑器