Custom pagination by array list
I SOLVED with this workaround.
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());
and I implemented a new custom comparator class
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);
}
}
}
Paginating an ArrayList
I would do it like this:
I'm not sure what renderValues does, and whether we have to substract 1 or maybe defaultStep from the upper bound of the moveCounter.
private void pageMove (int step)
{
moveCounter = moveCounter + step;
if (moveCounter < 0) moveCounter = 0;
if (moveCounter > values.size ()) moveCounter = values.size ();
renderValues (currentIndex, false);
}
private void pageNext ()
{
pageMove (defaultStep);
}
private void pagePrevious ()
{
pageMove (-defaultStep);
}
The first 3 lines could be packed into two big ternary experssions like so:
mc = ((mc + s) < 0) ? 0 : ((mc + s) > vs) ? vs : (mc + s);
but the 3 lines solution is better to follow.
Pagination From ArrayList in Android
try this
ArrayList<ItemCategory> arraylistsub = new ArrayList<>(Constant.arrayListCategories.subList(0,10));
How to implement pagination on a list?
I've solved this before. I made a static getPages method that breaks a generic collection into a list of pages (which are also lists). I've provided the code below.
public static <T> List<List<T>> getPages(Collection<T> c, Integer pageSize) {
if (c == null)
return Collections.emptyList();
List<T> list = new ArrayList<T>(c);
if (pageSize == null || pageSize <= 0 || pageSize > list.size())
pageSize = list.size();
int numPages = (int) Math.ceil((double)list.size() / (double)pageSize);
List<List<T>> pages = new ArrayList<List<T>>(numPages);
for (int pageNum = 0; pageNum < numPages;)
pages.add(list.subList(pageNum * pageSize, Math.min(++pageNum * pageSize, list.size())));
return pages;
}
How to create a pagination function with a given list
def paginator(array, page_number):
n, remainder = page_number, len(array) % page_number
curr, idx, old_idx = 1, 0, 0
while n + remainder != 0:
idx += len(array) // page_number + bool(remainder)
print(f"this is page {curr} have object {array[old_idx:idx]}")
n -= 1
remainder = max(remainder - 1, 0)
curr += 1
old_idx = idx
lst = list(range(1, 10))
page_number = 4
paginator(lst, page_number)
Prints:
this is page 1 have object [1, 2, 3]
this is page 2 have object [4, 5]
this is page 3 have object [6, 7]
this is page 4 have object [8, 9]
Java how to transform List<Object> to Page from JPA pagination
When you do custom queries and want to use Pageable, it's up to you to implement a logic to create a paging for your result list. In your case you aren't doing that so it's probably (you said it isn't working, but didn't say what isn't working so I can only guess) just returning the entire result list without paging applied.
A simple solution would be to use sublist
and use the result of that operation as your parameter for PageImpl
. Big problem is that you are still getting the entire result list from the database in the background which creates uneceassary overhead.
You could also adjust your query using
em.createQuery(query.where(predicate))
.setFirstResult(offset)
.setMaxResults(limit)
.getResultList()
Now the paging is done in the database which is a lot better.
Or you save yourself some trouble and use Springs Specification
interface instead of creating your own search method.
First your CarRepository
needs to extend JpaSpecificationExecutor
. Now spring will generate a findAll(Specification, Pageable)
method for your repository.
Second step is to create your search specification:
public class SearchSpecification implements Specification<Car> {
private final String brand;
private final String model
private final String type
private final Integer registrationYear
private final String color
private final String fuel
private final String transmission
private final String doors
private final double price
// constructor & maybe getter
public Predicate toPredicate(Root<Car> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
// Create your search predicate
}
}
Now you can simply call carRepository.findAll(new SearchSpecification (/* parameters */), pageable);
and spring does the paging for you.
Paginate Javascript array
You can use Array.prototype.slice
and just supply the params for (start, end)
.
function paginate(array, page_size, page_number) { // human-readable page numbers usually start with 1, so we reduce 1 in the first argument return array.slice((page_number - 1) * page_size, page_number * page_size);}
console.log(paginate([1, 2, 3, 4, 5, 6], 2, 2));console.log(paginate([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], 4, 1));
How to add PHP pagination in array's
u can use simple PHP function called array_slice()
$menuItems = array_slice( $menuItems, 0, 10 );
show first 10 items.
$menuItems = array_slice( $menuItems, 10, 10 );
show next 10 items.
UPDATE:
$page = ! empty( $_GET['page'] ) ? (int) $_GET['page'] : 1;
$total = count( $yourDataArray ); //total items in array
$limit = 20; //per page
$totalPages = ceil( $total/ $limit ); //calculate total pages
$page = max($page, 1); //get 1 page when $_GET['page'] <= 0
$page = min($page, $totalPages); //get last page when $_GET['page'] > $totalPages
$offset = ($page - 1) * $limit;
if( $offset < 0 ) $offset = 0;
$yourDataArray = array_slice( $yourDataArray, $offset, $limit );
UPDATE#2:
Example of pagination:
$link = 'index.php?page=%d';
$pagerContainer = '<div style="width: 300px;">';
if( $totalPages != 0 )
{
if( $page == 1 )
{
$pagerContainer .= '';
}
else
{
$pagerContainer .= sprintf( '<a href="' . $link . '" style="color: #c00"> « prev page</a>', $page - 1 );
}
$pagerContainer .= ' <span> page <strong>' . $page . '</strong> from ' . $totalPages . '</span>';
if( $page == $totalPages )
{
$pagerContainer .= '';
}
else
{
$pagerContainer .= sprintf( '<a href="' . $link . '" style="color: #c00"> next page » </a>', $page + 1 );
}
}
$pagerContainer .= '</div>';
echo $pagerContainer;
Related Topics
How to Return a List of Specific Type Instead of List<Object[]> in Hibernate
How to Do Post Request With Raw Data Via Spring Rest Template
How to Count the Rows in Hibernate Query Language
How to Send Text to Textarea in Div Element Using Selenium
How to Read Empty Cells of an Excel File Using Poi
Unable to Deploy Spring Boot 2 Application Due to Hikaripool Exception During Pool Initialization
How to Retrieve Mapping Table Name for an Entity in JPA At Runtime
How to Generate a Unique and Short File Name in Java
Regex, Remove Whitespace and All Other Characters
Several Ports (8005, 8080, 8009) Required by Tomcat Server At Localhost Are Already in Use
Optimizing Multiple If-Else Condition in Java
How to Restart a Java Program Here
Regular Expression to Match a Backslash Followed by a Quote
How to Scroll to the Bottom of a Recyclerview? Scrolltoposition Doesn't Work
Delete Not Working in Hibernate/Spring Data
Spring Data JPA Saveall Not Doing Batch Insert