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.

相关推荐
指针满天飞1 小时前
Collections.synchronizedList是如何将List变为线程安全的
java·数据结构·list
洋曼巴-young1 小时前
240. 搜索二维矩阵 II
数据结构·算法·矩阵
楼田莉子3 小时前
C++算法题目分享:二叉搜索树相关的习题
数据结构·c++·学习·算法·leetcode·面试
小明的小名叫小明3 小时前
区块链技术原理(14)-以太坊数据结构
数据结构·区块链
pusue_the_sun3 小时前
数据结构——栈和队列oj练习
c语言·数据结构·算法··队列
奶黄小甜包4 小时前
C语言零基础第18讲:自定义类型—结构体
c语言·数据结构·笔记·学习
想不明白的过度思考者4 小时前
数据结构(排序篇)——七大排序算法奇幻之旅:从扑克牌到百亿数据的魔法整理术
数据结构·算法·排序算法
一支闲人4 小时前
C语言相关简单数据结构:双向链表
c语言·数据结构·链表·基础知识·适用于新手小白
姜不吃葱5 小时前
【力扣热题100】双指针—— 接雨水
数据结构·算法·leetcode·力扣热题100
拂晓银砾5 小时前
Java数据结构-队列
java·数据结构