Search code examples
javaspringspring-data-jpapagination

Implement Paging for Java Map


I have this Map of Java objects which I would like to display as pages into UI:

 Map<Integer, CategoryFullDTO> list = new HashMap<>();

 list.put(1, CategoryFullDTO.builder().id(1).title("item 1").build());
 list.put(2, CategoryFullDTO.builder().id(2).title("item 2").build());
 list.put(3, CategoryFullDTO.builder().id(3).title("item 3").build());

I create Pages object using:

 final Page<Map<Integer, CategoryFullDTO>> page = new PageImpl<>(list);

but I get Cannot infer arguments

How I can spring the map into lists and get a page by page?


Solution

  • If the PageImpl is from the springframework.data.domain, then the constructor takes a List argument and not a Map object as argument.

    So you could try

    Map<Integer, CategoryFullDTO> map= new HashMap<>();
    
    map.put(1, CategoryFullDTO.builder().id(1).title("item 1").build());
    map.put(2, CategoryFullDTO.builder().id(2).title("item 2").build());
    map.put(3, CategoryFullDTO.builder().id(3).title("item 3").build());
    
    List<Map<Integer, CategoryFullDTO>> list = new ArrayList<>();
    list.add(map);
    final Page<Map<Integer, CategoryFullDTO>> page = new PageImpl<>(list);