![](/img/trans.png)
[英]How to convert List<String> to JsonNode. I want to remove elements from List
[英]How can I use loop here, I want to remove 3 elements from list for every turn
我有一個包含一些元素的列表,我需要在第 num = 1 頁時打印前 3 個元素,然后在 page ==2 時打印下 3 個元素
public class OtherTemporaryTrials {
public static void main(String[] args) {
int numOfPages = 6;
ArrayList<Integer> al = new ArrayList<Integer>();
al.add(13);
al.add(77);
al.add(53);
al.add(63);
al.add(173);
al.add(134);
al.add(1366);
al.add(13446);
al.add(1333);
al.add(1323);
al.add(163);
al.add(1335);
al.add(13228);
al.add(1573);
al.add(13355);
al.add(12343);
al.add(12353);
for(int i=0;i<numOfPages;i++) {
setdata(al,numOfPages);
}
}
private static void setdata(ArrayList<Integer> al, int numOfPages) {
for(int i=0;i<3;i++) {
// Here for every next page we should get the next 3 elements from List
System.out.println(al.get(i));
}
}
}
要訪問頁面大小為k
的nth
頁,您需要獲取n * k
到(n + 1) * k
范圍內的元素。 這可以使用subList
API 輕松完成:
public class Main {
public static List<Integer> getPage(List<Integer> list, int pageSize, int pageNo) {
// get the from & to range bounds, respecting the list length to prevent IndexOutOfBound exceptions
int from = pageNo * pageSize;
int to = Math.min(list.size(), (pageNo + 1) * pageSize);
// return the expected slice of the list
return list.subList(from, to);
}
public static void clearPage(List<Integer> list, int pageSize, int pageNo) {
// get the from & to range bounds, respecting the list length to prevent IndexOutOfBound exceptions
int from = pageNo * pageSize;
int to = Math.min(list.size(), (pageNo + 1) * pageSize);
// clear the expected slice from the list
// this is allowed as long as the list is not "read-only"
list.subList(from, to).clear();
}
public static void main(String[] args) {
// need to use an array list because Arrays.asList return an immutable list (read-only)
var list = new ArrayList<Integer>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
int pageSize = 3;
// print pages
System.out.println(getPage(list, pageSize, 0));
System.out.println(getPage(list, pageSize, 1));
System.out.println(getPage(list, pageSize, 2));
System.out.println(getPage(list, pageSize, 3));
System.out.println(list);
// delete elements at position 0 to 2
clearPage(list, pageSize, 0);
System.out.println(list);
// delete elements at position 3 to 5
clearPage(list, pageSize, 1);
System.out.println(list);
}
}
因為這適用於從零開始的索引,如果您希望 1 表示第一頁,則需要先從頁碼中減去 1,然后才能使用它來計算 subList 的范圍邊界。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.