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.

相关推荐
Logic1012 小时前
C语言/数据结构位运算题解:异或XOR找出蛋糕订单中的“VIP独特口味“——只出现一次的数字
c语言·数据结构·数组·位运算·时间复杂度·算法题·异或性质
Logic1013 小时前
C语言/数据结构位运算题解:异或XOR找出飞行棋中的“独特颜色棋子“——只出现一次的数字
c语言·数据结构·数组·位运算·时间复杂度·算法题·异或性质
爱吃苹果的日记本3 小时前
数据结构第三课(时间复杂度)
数据结构·学习
Logic1014 小时前
C语言/数据动态规划题解:翻转一次子数组后的最大子数组和——四状态DP(O(n)时间O(1)空间)
c语言·数据结构·动态规划·时间复杂度·算法题·状态机dp·最大子数组和
小π军5 小时前
最大重叠区间数量
数据结构·算法
Logic1016 小时前
C语言/数据结构字符串题解:找出DNA序列中未配对的独特序列——排序+遍历(O(nlogn))
c语言·数据结构·字符串·数组·排序·时间复杂度·算法题
江湖人称菠萝包6 小时前
【Windows】《深入浅出Windows API程序设计:核心编程篇》笔记-Chapter4-进程
windows·笔记
wzdark7 小时前
基于链表的内存池设计与内存复用机制4
java·数据结构·链表
www.028 小时前
Codex额度用完怎么办?Windows定时自动继续VS Code Codex任务实战
人工智能·windows·vscode·自动化·openai·codex·autohotkey
BizzZ_9 小时前
算法(1)——双指针
数据结构