How to return just one string from java stream

  • A+
Category:Languages

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.

 


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*/)); 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: