3
Page<K2Agents> iterable = k2AgentsRepository.findAllByTeamIdIn(teamIds, pageRequest);
List<K2Agents> iterable1 = iterable.stream()
                                   .filter(i->i.getLastName().equals(searchName))
                                   .collect(Collectors.toList());
return iterable1;

I want to filter iterable by a string searchName. The final result should be a Page. In this code iterable1 return nothing.

Pshemo
  • 122,468
  • 25
  • 185
  • 269
Mike280977
  • 33
  • 1
  • 6
  • 1
    What do you mean by "final result should be a `Page`"? Also "In this code iterable1 return nothing" is confusing since `.collect(Collectors.toList())` ensures that result will be `List`, possibly empty but still a list so it is not nothing (I know it is nitpicking but to get correct answers it is good to be as precise as we can). – Pshemo Jul 29 '19 at 10:49
  • I mean iterable1 should return a Page. I printed iterable and it returns a Page, but iterables1 returns nothing. thx – Mike280977 Jul 29 '19 at 11:10
  • Try this `iterable.map(k2Agent -> k2Agent.getLastName().equals(searchName) ? k2Agent : null);` – Hadi J Jul 29 '19 at 11:10
  • You should not do what you write in the text because it breaks the semantic Page contract which promises that the Page has either a given size or there is no next Page. Either do the filtering on the database (which would be smart anyways) or you return a List (which your code already does). In the later case you should use page.filter().get().collect(). – Christoph Grimmer Jul 29 '19 at 11:37
  • Possible duplicate of [How to convert a List of enity Object to Page Object in Spring Mvc Jpa?](https://stackoverflow.com/questions/37136679/how-to-convert-a-list-of-enity-object-to-page-object-in-spring-mvc-jpa) – Muhammad Usman Jul 29 '19 at 11:43

1 Answers1

6

First filter the Page<K2Agent> by using stream and finally create Page object using PageImpl

List<K2Agents> result = iterable.getContent()
                                   .stream()
                                   .filter(i->i.getLastName().equals(searchName))
                                   .collect(Collectors.toList());

Page<K2Agent> r = new PageImpl<K2Agent>(result);
Ryuzaki L
  • 37,302
  • 12
  • 68
  • 98