Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thymeleaf iterating a Java 8 Stream from Spring Data JPA

My Google-Fu is failing me so I ask you... Is there a way to iterate a Java 8 Stream with Thymeleaf similar the way one iterates a List while still keeping Stream's performance purpose?

Repository

Stream<User> findAll()

Model

Stream<User> users = userRepository.findAll();
model.addAttribute("users", users);

View

<div th:each="u: ${users}">
   <div th:text="${u.name}">

If I try this, I get:

org.springframework.expression.spel.SpelEvaluationException: EL1008E: Property or field 'name' cannot be found on object of type 'java.util.stream.ReferencePipeline$Head' - maybe not public?

If I use a List instead, it works as expected.

Is there a proper way to handle a Stream that I'm failing to find?

like image 446
Marcelus Trojahn Avatar asked Nov 23 '25 08:11

Marcelus Trojahn


2 Answers

While Thymeleaf doesn't support streams as per the documentation it does support Iterable, so you can do the following:

Model:

Stream<User> users = userRepository.findAll();
model.addAttribute("users", (Iterable<User>) users::iterator);

And your view will work as you have already written it:

<div th:each="u: ${users}">
    <div th:text="${u.name}">

Looking at the version 3 documentation it says that it will support any object which implements Iterator so it should also be possible to do this:

Model:

Stream<User> users = userRepository.findAll();
model.addAttribute("users", users.iterator());

I'm not using that version, so I haven't been able to get that to work though.

like image 98
Julian Avatar answered Nov 24 '25 23:11

Julian


As far as I know and looking on the Thymeleaf documentation there is no way to do what you want.

Besides Thymeleaf doesn't provide any way to interact with streams, take into account that Stream objects hasn't access to its contained objects till you do a terminal operation (for example Collectors.toList())

like image 29
exoddus Avatar answered Nov 24 '25 23:11

exoddus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!