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.

相关推荐
慢半拍iii13 分钟前
数据结构——F/图
c语言·开发语言·数据结构·c++
iceslime1 小时前
旅行商问题(TSP)的 C++ 动态规划解法教学攻略
数据结构·c++·算法·算法设计与分析
witton3 小时前
美化显示LLDB调试的数据结构
数据结构·python·lldb·美化·debugger·mupdf·pretty printer
chao_7893 小时前
链表题解——环形链表 II【LeetCode】
数据结构·leetcode·链表
nenchoumi31194 小时前
AirSim/Cosys-AirSim 游戏开发(一)XBox 手柄 Windows + python 连接与读取
windows·python·xbox
kaiaaaa4 小时前
算法训练第十一天
数据结构·算法
love530love5 小时前
【PyCharm必会基础】正确移除解释器及虚拟环境(以 Poetry 为例 )
开发语言·ide·windows·笔记·python·pycharm
-qOVOp-5 小时前
408第一季 - 数据结构 - 图II
数据结构
-qOVOp-5 小时前
408第一季 - 数据结构 - 树与二叉树III
数据结构
lifallen5 小时前
深入浅出 Arrays.sort(DualPivotQuicksort):如何结合快排、归并、堆排序和插入排序
java·开发语言·数据结构·算法·排序算法