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.

相关推荐
xie_pin_an1 小时前
深入浅出 C 语言数据结构:从线性表到二叉树的实战指南
c语言·数据结构·图论
tang&1 小时前
滑动窗口:双指针的优雅舞步,征服连续区间问题的利器
数据结构·算法·哈希算法·滑动窗口
Nandeska2 小时前
2、数据库的索引与底层数据结构
数据结构·数据库
秋田君3 小时前
前端工程化部署入门:Windows + Nginx 实现多项目独立托管与跨域解决方案
前端·windows·nginx
又是忙碌的一天4 小时前
二叉树的构建与增删改查(2) 删除节点
数据结构
Code Slacker4 小时前
LeetCode Hot100 —— 滑动窗口(面试纯背版)(四)
数据结构·c++·算法·leetcode
不起眼的小草5 小时前
windows系统使用nvm配置自动切换node版本
windows
F_D_Z5 小时前
最长连续序列(Longest Consecutive Sequence)
数据结构·算法·leetcode
WolfGang0073216 小时前
代码随想录算法训练营Day50 | 拓扑排序、dijkstra(朴素版)
数据结构·算法