I understand how to collect to a List
, but can't figure
how I would return just one parameter of filtered object as a String
.
fee = new BigDecimal(fees
.stream()
.filter(p -> p.getTodate().isAfter(LocalDateTime.now()))
.filter(p -> p.getFromdate().isBefore(LocalDateTime.now()))
.filter(p -> p.getId().equals(id))
return fee;
I first check that the fee is up to date, as there might be upcoming fees and fees that are no longer valid. Then I match the id with remaining fees. But then there is code missing between last filter and return.
I just want to return String
from Stream
object (p.getFee) for BigDecimal
constructor.
I know there is only one Stream
object remaining after filters.
Using Stream findFirst() Method: The findFirst() method will returns the first element of the stream or an empty if the stream is empty. Approach: Get the stream of elements in which the first element is to be returned. To get the first element, you can directly use the findFirst() method.
We can use Stream collect() function to perform a mutable reduction operation and concatenate the list elements. The supplier function is returning a new StringBuilder object in every call. The accumulator function is appending the list string element to the StringBuilder instance.
You can leverage Java 8 Collectors to concatenate some objects into a string separated by a delimiter: For example: List<Integer> numbers = Arrays. asList( 4, 8, 15, 16, 23, 42 ); return numbers.
Use findFirst
to return the first element of the Stream
that passes your filters. It returns an Optional
, so you can use orElse()
to set a default value in case the Stream
is empty.
fee = new BigDecimal(fees
.stream()
.filter(p -> p.getTodate().isAfter(LocalDateTime.now()))
.filter(p -> p.getFromdate().isBefore(LocalDateTime.now()))
.filter(p -> p.getId().equals(id))
.map(p -> p.getFee())
.findFirst()
.orElse(/*some default value*/));
Maybe it would be a better approach:
fee = fees.stream()
.filter(p -> p.getTodate().isAfter(LocalDateTime.now()))
.filter(p -> p.getFromdate().isBefore(LocalDateTime.now()))
.filter(p -> p.getId().equals(id))
.map(p -> p.getFee())
.findFirst()
.map(BigDecimal::new)
.orElse(/*some default value*/);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With