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:
-
Initialization : We initialize
sydfList
withBigDecimal
objects. -
Finding Maximum Value:
- We use
stream()
onsydfList
to convert it into a stream ofBigDecimal
. max()
function is applied on the stream to find the maximum value.BigDecimal::compareTo
is used as the comparator to determine the ordering ofBigDecimal
objects.orElse(BigDecimal.ZERO)
ensures that if the stream is empty, we default toBigDecimal.ZERO
.
- We use
-
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.
- Similarly,
-
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.