View Javadoc
1   /*
2    * Licensed to The Apereo Foundation under one or more contributor license
3    * agreements. See the NOTICE file distributed with this work for additional
4    * information regarding copyright ownership.
5    *
6    *
7    * The Apereo Foundation licenses this file to you under the Educational
8    * Community License, Version 2.0 (the "License"); you may not use this file
9    * except in compliance with the License. You may obtain a copy of the License
10   * at:
11   *
12   *   http://opensource.org/licenses/ecl2.txt
13   *
14   * Unless required by applicable law or agreed to in writing, software
15   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
16   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
17   * License for the specific language governing permissions and limitations under
18   * the License.
19   *
20   */
21  
22  package org.opencastproject.util;
23  
24  import java.util.ArrayList;
25  import java.util.Collection;
26  import java.util.Iterator;
27  import java.util.LinkedHashMap;
28  import java.util.List;
29  import java.util.Map;
30  import java.util.Map.Entry;
31  
32  /**
33   * Utility class for applying limit and offset to a map or collection
34   */
35  public class SmartIterator<A> {
36    private int limit;
37    private int offset;
38    private Iterator<?> iterator;
39  
40    public SmartIterator(int limit, int offset) {
41      this.limit = limit;
42      this.offset = offset;
43    }
44  
45    /**
46     * Apply limit and offset to a map of value type {@link A}
47     *
48     * @param map
49     *          the map
50     * @return the filtered map
51     */
52    public Map<String, A> applyLimitAndOffset(Map<String, A> map) {
53      iterator = map.entrySet().iterator();
54  
55      Map<String, A> filteredMap = new LinkedHashMap<String, A>();
56      int i = 0;
57      while (isRecordRequired(filteredMap.size())) {
58        Entry<String, A> item = (Entry<String, A>) iterator.next();
59        if (i++ >= offset) {
60          filteredMap.put(item.getKey(), item.getValue());
61        }
62      }
63      return filteredMap;
64    }
65  
66    private boolean isRecordRequired(int filteredMapSize) {
67      return (filteredMapSize < limit || limit == 0) && iterator.hasNext();
68    }
69  
70    /**
71     * Apply limit and offset to a collection of type {@link A}
72     *
73     * @param unfilteredCollection
74     *          the collection
75     * @return the filtered list
76     */
77    public List<A> applyLimitAndOffset(Collection<A> unfilteredCollection) {
78      iterator = unfilteredCollection.iterator();
79      List<A> filteredList = new ArrayList<A>();
80      int i = 0;
81      while (isRecordRequired(filteredList.size())) {
82        A nextItem = (A) iterator.next();
83        if (i++ >= offset) {
84          filteredList.add(nextItem);
85        }
86      }
87      return filteredList;
88    }
89  }