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.

相关推荐
minji...2 小时前
数据结构 堆(4)---TOP-K问题
java·数据结构·算法
codebetter3 小时前
Windows子系统WSL Ubuntu24.04 Docker pull镜像失败
windows·docker
落羽的落羽3 小时前
【C++】论如何封装红黑树模拟实现set和map
数据结构·c++·学习
kyle~4 小时前
Windows---动态链接库Dynamic Link Library(.dll)
运维·windows·操作系统·运维开发·开发部署
一百天成为python专家4 小时前
K-近邻算法
数据结构·python·算法·pandas·近邻算法·ipython·python3.11
小新学习屋4 小时前
《剑指offer》-数据结构篇-哈希表/数组/矩阵/字符串
数据结构·leetcode·哈希表
中游鱼6 小时前
如何序列化和反序列化动态 XmlElement ?
windows·microsoft·c#
我命由我1234511 小时前
Kotlin 数据容器 - List(List 概述、创建 List、List 核心特性、List 元素访问、List 遍历)
java·开发语言·jvm·windows·java-ee·kotlin·list
mCell13 小时前
从删库到跑路?这50个Linux命令能保你职业生涯
linux·windows·macos
dualven_in_csdn13 小时前
electron 使用记录
windows