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 分钟前
数据结构----插入排序
数据结构·算法·排序算法
im_AMBER2 分钟前
Leetcode 162 除了自身以外数组的乘积 | 接雨水
开发语言·javascript·数据结构·算法·leetcode
cpp_250113 分钟前
P1873 [COCI 2011/2012 #5] EKO / 砍树
数据结构·c++·算法·题解·二分答案·洛谷·csp
啊哦呃咦唔鱼15 分钟前
leetcodehot100-347. 前 K 个高频元素
数据结构·算法·leetcode
V我五十买鸡腿26 分钟前
网安基础 Windows 和 Linux 那些常用命令
linux·运维·windows
handler0140 分钟前
进程状态流转的本质:Linux 内核队列与底层数据结构解密
linux·运维·c语言·数据结构·c++·笔记·学习
自我意识的多元宇宙1 小时前
数据结构--散列函数的构造方法
数据结构
如君愿1 小时前
考研复习 Day 25 | 习题--计算机网络第三章(数据链路层 上)、数据结构(串)
数据结构·计算机网络·考研
夏末蝉未鸣011 小时前
Sort-Merge Join【排序连接算法】详解(python代码实现,以FULL JOIN为例)
数据结构·算法
_日拱一卒1 小时前
LeetCode:23合并K个升序链表
java·数据结构·算法·leetcode·链表·职场和发展