通过数组列表自定义分页

问题描述 投票:0回答:5

我想在java代码中通过数组列表创建自定义分页

import org.springframework.data.domain.Sort;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Sort.Direction;
...    

    int page = 0;
    int count = 8;
    String sortOrder = "desc";
    String sortBy = "id";

    Sort sort = new Sort(Direction.fromString(sortOrder), sortBy);
    PageRequest pageable = new PageRequest(page, count, sort);

    List<Impianto> impiantos = myService.findMyMethod(); // returned 30 objects 
    Page<Impianto> pageImpianto = new PageImpl<Impianto>(impiantos, pageable, impiantos.size()); 

上面的脚本不返回包含 8 个元素的页面。为什么?

注意该列表没有从数据库返回

你能帮我吗?

java spring arraylist pagination
5个回答
5
投票

我用这个解决方法解决了

    import org.springframework.data.domain.Sort;
    import org.springframework.data.domain.PageRequest;
    import org.springframework.data.domain.Page;
    import org.springframework.data.domain.PageImpl;
    import org.springframework.data.domain.Sort.Direction;
    ...    

        int page = 0;
        int count = 8;
        String sortOrder = "desc";
        String sortBy = "id";

        Sort sort = new Sort(Direction.fromString(sortOrder), sortBy);
        PageRequest pageable = new PageRequest(page, count, sort);

        List<Impianto> impiantos = myService.findMyMethod(); // returned 30 objects 
        int max = (count*(page+1)>impiantos.size())? impiantos.size(): count*(page+1);

        Page<Impianto> pageImpianto = new PageImpl<Impianto>(impiantos.subList(page*count, max), pageable, impiantos.size());  

我实现了一个新的自定义比较器类

import java.lang.reflect.Field;
import java.util.Comparator;
import java.util.Date;

public class MyListComparator implements Comparator<Object> {

    final String sortBy;
    final String sortOrder;

    public MyListComparator(String sortBy, String sortOrder) {
        this.sortBy = sortBy;
        this.sortOrder = sortOrder;
    }

    @Override
    public int compare(Object o1, Object o2) {

        try {
            Field field1 = o1.getClass().getDeclaredField(sortBy);
            Field field2 = o2.getClass().getDeclaredField(sortBy);

            field1.setAccessible(true); // because the fields in Impianto entity has "private" 
            field2.setAccessible(true);

            if(o1.getClass().getDeclaredField(sortBy).getType() == Long.class){
                Long d1 = (Long) field1.get(o1);
                Long d2 = (Long) field2.get(o2);
                return (sortOrder.toLowerCase().equals("asc"))? d1.compareTo(d2) : d2.compareTo(d1);

            }else if(o1.getClass().getDeclaredField(sortBy).getType() == Date.class){
                Date d1 = (Date) field1.get(o1);
                Date d2 = (Date) field2.get(o2);
                return (sortOrder.toLowerCase().equals("asc"))? d1.compareTo(d2) : d2.compareTo(d1);

            }else{
                String d1 = (String) field1.get(o1);
                String d2 = (String) field2.get(o2);
                return (sortOrder.toLowerCase().equals("asc"))? d1.compareTo(d2) : d2.compareTo(d1);

            }
        } catch (SecurityException e) {
            throw new RuntimeException(e);
        } catch (NoSuchFieldException e) {
            throw new RuntimeException("Missing variable sortBy");
        }catch (ClassCastException e) {
            throw new RuntimeException("sortBy is not found in class list");
        } catch (IllegalArgumentException e) {
            //shoud not happen
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }


}

1
投票

我根据您编写了自己的代码,以满足客户的要求,没有排序等。 谢谢你

这就是控制器的样子

    @RequestMapping(value="/zonas", method = RequestMethod.GET)
public String zonas(ModelMap modelMap, @PageableDefault(size=3) Pageable pageable, ZonasFilter zonasFilter, Locale locale) {
    LOGGER.info("Cargando la vista del índice de Zonas.");
    List<Zona> zonas;
    try {
        zonas = zonasService.loadAll();
        int max = (pageable.getPageSize()*(pageable.getPageNumber()+1)>zonas.size())? zonas.size(): pageable.getPageSize()*(pageable.getPageNumber()+1);
        modelMap.addAttribute("zonas",new PageImpl<Zona>(zonas.subList(pageable.getPageSize()*pageable.getPageNumber(), max), pageable, zonas.size()));
    } catch (ApiException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        List<ApiError> errors=e.getErrors(); 
        for (ApiError apiError : errors) {
            modelMap.addAttribute("error", messages.getMessage(apiError.getMessage(), null, locale));
        }

    }   
    LOGGER.info("Vista del índice de  Zonascargada.");
    return "zonas/index";
}

1
投票

对我来说它有效

Page<OrderLineDTO> toPage(List<OrderLineDTO> list, int pagesize, int pageNo) {

    int totalpages = list.size() / pagesize;
        PageRequest pageable = new PageRequest(pageNo, pagesize);

        int max = pageNo>=totalpages? list.size():pagesize*(pageNo+1);
        int min = pageNo >totalpages? max:pagesize*pageNo;

        logger.info("totalpages{} pagesize {} pageNo {}   list size {} min {}   max {} ...........", totalpages,pagesize, pageNo, list.size(),
                min, max);
        Page<OrderLineDTO> pageResponse = new PageImpl<OrderLineDTO>(list.subList(min, max), pageable,
                list.size());
        return pageResponse;
    }

0
投票

Flavio Troia的答案是错误的,当impiantos小于count且page大于1时,调用subList函数时会出现异常, fromIndex(10) > toIndex(5) ,我自己编写了这样的代码,它是也许是多余的,但对我来说很容易理解也没错~

 List<UcShopCourseBizPojo> shopCourseBizPojos = addCourseCoupons(mcCouponLists, shopCourseLists);


        if (pageable.getOffset() > shopCourseBizPojos.size()) {
            long total = 0L;
            PageImpl<UcShopCourseBizPojo> emptyPage = new PageImpl<>(Lists.newArrayList(), pageable, total);
            resultDo.setResult(emptyPage);
            return resultDo;
        }

        if (pageable.getOffset() <= shopCourseBizPojos.size() && pageable.getOffset() + pageable.getPageSize() > shopCourseBizPojos.size()) {
            List<UcShopCourseBizPojo> bizPojos = shopCourseBizPojos.subList(pageable.getOffset(), shopCourseBizPojos.size());
            PageImpl<UcShopCourseBizPojo> pPage = new PageImpl<>(bizPojos, pageable, shopCourseLists.size());
            resultDo.setResult(pPage);
            return resultDo;
        }

        List<UcShopCourseBizPojo> ucShopCourseBizPojos = shopCourseBizPojos.subList(pageable.getOffset(), pageable.getOffset() + pageable.getPageSize());

        PageImpl<UcShopCourseBizPojo> pPage = new PageImpl<>(ucShopCourseBizPojos, pageable, shopCourseLists.size());
        resultDo.setResult(pPage);
        return resultDo;

0
投票

我喜欢这个最大值和最小值(列表大小的最小值和(pageSize * pageNo))

Page toPageOrderCache(List list, int pageSize, int pageNo) { 列表排序 = list.stream().sorted(Comparator.comparing(Model::getString).reversed()).toList(); // 使用比较器对列表进行排序 PageRequest 可分页 = PageRequest.of(pageNo, pageSize);

    int max = Math.min(pageSize * (pageNo + 1), list.size());
    int min = Math.min(pageSize * pageNo, list.size());

    getLogger().info("paginate Models by pageSize: ({}), pageNo: ({}) ,list size: ({}), min: ({}), max: ({}) ", pageSize, pageNo, list.size(),
            min, max);
    return new PageImpl<Model>(sorted.subList(min, max), pageable, list.size());
}
© www.soinside.com 2019 - 2024. All rights reserved.