How to paginate a list of objects in Java 8?

后端 未结 3 1403
离开以前
离开以前 2020-12-05 05:50

Given a java.util.List with n elements and a desired page size m, I want to transform it to a map containing n/m+n%m elem

3条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-05 06:07

    As noted in the comments this also works if the list is not a natural sequence of integers. You would have to use a generated IntStream then and refer to the elements in list by index.

    List list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
    
    Map map = IntStream
        .range(0, list.size())
        .boxed()
        .collect(groupingBy(
            i -> i / 3, //no longer i-1 because we start with 0
            mapping(i -> list.get((int) i).toString(), joining(","))
            ));
    
    //result: {0="1,2,3", 1="4,5,6", 2="7,8,9", 3="10"}
    

    We start with an IntStream representing the indices of the list.

    groupingBy groups the elements by some classifier. In your case it groups x elements per page.

    mapping applies a mapping function to the elements and collects them afterwards. The mapping is necessary because joiningonly accepts CharSequence. joining itself joins the elements by using an arbitrary delimiter.

提交回复
热议问题