Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return just one string from java stream

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.

like image 507
Clomez Avatar asked Nov 09 '18 08:11

Clomez


People also ask

How do I get one element from a stream list?

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.

How do you collect stream strings?

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.

How do you collect a string in Java?

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.


2 Answers

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*/));
like image 99
Eran Avatar answered Oct 10 '22 23:10

Eran


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*/);
like image 22
Piotr Rzonsowski Avatar answered Oct 10 '22 22:10

Piotr Rzonsowski