BrightSide Workbench Full Report + Source Code
CollectionIterator.java
Go to the documentation of this file.
1 /*
2  * TurrĂ³ i Cutiller Foundation. License notice.
3  * Copyright (C) 2018 Lluis TurrĂ³ Cutiller <http://www.turro.org/>
4  *
5  * This program is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU Affero General Public License as published by
7  * the Free Software Foundation, either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  * GNU Affero General Public License for more details.
14  *
15  * You should have received a copy of the GNU Affero General Public License
16  * along with this program. If not, see <http://www.gnu.org/licenses/>.
17  */
18 
19 package org.turro.collections;
20 
21 import java.util.List;
22 
27 public abstract class CollectionIterator<E, ID> {
28 
29  protected List<E> items, collection;
30  protected int _total = -1;
31 
32  private int _page = 10, _curr = -1;
33  private boolean end;
34 
35  public CollectionIterator(List<E> collection) {
36  this.collection = collection;
37  }
38 
39  public int getPage() {
40  return _page;
41  }
42 
43  public void setPage(int page) {
44  this._page = page;
45  }
46 
47  public void initClauses() {
48  _curr = -1;
49  end = false;
50  _total = -1;
51  getTotalCount();
52  }
53 
54  public List<E> getItems() {
55  return items;
56  }
57 
58  public int getTotalCount() {
59  if(_total == -1) {
60  _total = collection.size();
61  }
62  return _total;
63  }
64 
65  public List<E> getTotalItems() {
66  return collection;
67  }
68 
69  public int item() {
70  return _curr;
71  }
72 
73  public void current(int value) {
74  value = (value * _page) - _page;
75  if(value >= _total) {
76  value = _total - _page;
77  end = true;
78  }
79  if(value < 0) {
80  _curr = 0;
81  } else {
82  _curr = value;
83  }
84  loadItems();
85  }
86 
87  public int current() {
88  if(_curr > -1) {
89  return (int) Math.ceil((_curr) / (_page + 0.0d));
90  }
91  return -1;
92  }
93 
94  public int pages() {
95  if(_total > -1) {
96  return (int) Math.ceil((_total + 0.0d) / (_page + 0.0d));
97  }
98  return -1;
99  }
100 
101  public boolean beginning() {
102  return _curr <= 0;
103  }
104 
105  public boolean end() {
106  return end;
107  }
108 
109  public void next() {
110  current(current() + 1);
111  }
112 
113  public void previous() {
114  current(current() - 1);
115  }
116 
117  public boolean isEmpty() {
118  return items == null || items.isEmpty();
119  }
120 
121  private void loadItems() {
122  items = collection.subList(_curr, Math.min(_curr + _page, _total));
123  }
124 
125 }
126