source: josm/trunk/src/org/openstreetmap/josm/tools/SubclassFilteredCollection.java@ 8961

Last change on this file since 8961 was 8836, checked in by Don-vip, 9 years ago

fix Checkstyle issues

  • Property svn:eol-style set to native
File size: 2.7 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.tools;
3
4import java.util.AbstractCollection;
5import java.util.Collection;
6import java.util.Iterator;
7
8/**
9 * Filtered view of a collection.
10 * (read-only collection, but elements can be changed, of course)
11 * Lets you iterate through those elements of a given collection that satisfy a
12 * certain condition (imposed by a predicate).
13 * @param <S> element type of the underlying collection
14 * @param <T> element type of filtered collection (and subclass of S). The predicate
15 * must accept only objects of type T.
16 * @since 3147
17 */
18public class SubclassFilteredCollection<S, T extends S> extends AbstractCollection<T> {
19
20 private final Collection<? extends S> collection;
21 private final Predicate<? super S> predicate;
22 private int size = -1;
23
24 private class FilterIterator implements Iterator<T> {
25
26 private final Iterator<? extends S> iterator;
27 private S current;
28
29 FilterIterator(Iterator<? extends S> iterator) {
30 this.iterator = iterator;
31 }
32
33 private void findNext() {
34 if (current == null) {
35 while (iterator.hasNext()) {
36 current = iterator.next();
37 if (predicate.evaluate(current))
38 return;
39 }
40 current = null;
41 }
42 }
43
44 @Override
45 public boolean hasNext() {
46 findNext();
47 return current != null;
48 }
49
50 @SuppressWarnings("unchecked")
51 @Override
52 public T next() {
53 findNext();
54 S old = current;
55 current = null;
56 // we are save because predicate only accepts objects of type T
57 return (T) old;
58 }
59
60 @Override
61 public void remove() {
62 throw new UnsupportedOperationException();
63 }
64 }
65
66 /**
67 * Constructs a new {@code SubclassFilteredCollection}.
68 * @param collection The base collection to filter
69 * @param predicate The predicate to use as filter
70 */
71 public SubclassFilteredCollection(Collection<? extends S> collection, Predicate<? super S> predicate) {
72 this.collection = collection;
73 this.predicate = predicate;
74 }
75
76 @Override
77 public Iterator<T> iterator() {
78 return new FilterIterator(collection.iterator());
79 }
80
81 @Override
82 public int size() {
83 if (size == -1) {
84 size = 0;
85 Iterator<T> it = iterator();
86 while (it.hasNext()) {
87 size++;
88 it.next();
89 }
90 }
91 return size;
92 }
93
94 @Override
95 public boolean isEmpty() {
96 return !iterator().hasNext();
97 }
98}
Note: See TracBrowser for help on using the repository browser.