Skip to content

Instantly share code, notes, and snippets.

@whatvn
Last active Apr 27, 2017
Embed
What would you like to do?
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* Created by Hung on 4/27/17.
*/
public class ListOperator {
public static class Order {
public int orderNumber;
public Order(int orderNumber) {
this.orderNumber = orderNumber;
}
public String toString() {
return "Order(" + this.orderNumber + ")";
}
}
public static <T> List<T> getPage(List<T> sourceList, int page, int pageSize) {
if (pageSize <= 0 || page <= 0) {
throw new IllegalArgumentException("invalid page size: " + pageSize);
}
int fromIndex = (page - 1) * pageSize;
if (sourceList == null || sourceList.size() < fromIndex) {
return Collections.emptyList();
}
// toIndex exclusive
return sourceList.subList(fromIndex, Math.min(fromIndex + pageSize, sourceList.size()));
}
public static void main(String[] args) {
List<Order> orders = Arrays.asList(new Order(1), new Order(2), new Order(-1), new Order(-2), new Order(6), new Order(6),
new Order(10), new Order(11), new Order(12), new Order(100));
int pageSize = 3; // của em là 100
int totalPage = orders.size() % pageSize == 0 ? orders.size() / pageSize : orders.size() / pageSize + orders.size() % pageSize;
System.out.println(totalPage);
for (int i = 1; i <= totalPage; i++) {
List<Order> page = getPage(orders, i, pageSize);
ArrayList<Order> results = new ArrayList<>();
for (Order order : page) {
if (order.orderNumber > 0) {
results.add(order);
}
}
System.out.println(results);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment