01: package snow.utils;
02:
03: import java.util.*;
04:
05: /** Some utilities in addition to java.util.Collections
06: */
07: public final class CollectionUtils {
08: private CollectionUtils() {
09: }
10:
11: /** {1,2,3,4,5,6}, 3 => {1,2,3}
12: */
13: public final static <T> Collection<T> takeFirst(
14: final Collection<T> c1, final int n) {
15: List<T> lt = new ArrayList<T>();
16: final Iterator<T> it = c1.iterator();
17: int i = 0;
18: while (it.hasNext() && i < n) {
19: lt.add(it.next());
20: i++;
21: }
22: return lt;
23: }
24:
25: /** {1,2,3,4,5,6}, 3 => {6,5,4}
26: */
27: public final static <T> List<T> takeLast(final List<T> c1,
28: final int n) {
29: List<T> lt = new ArrayList<T>();
30:
31: for (int i = c1.size() - 1; i >= 0; i--) {
32: lt.add(c1.get(i));
33: if (lt.size() >= n)
34: break;
35: }
36: return lt;
37: }
38:
39: /** @return the set of elements that are present in both sets given as arguments.
40: */
41: public final static <T> Set<T> intersection(
42: final Collection<T> set1, final Collection<T> set2) {
43: final Set<T> both = new HashSet<T>();
44:
45: // just look which elements of set1 are present in set2
46: Iterator<T> iter = set1.iterator();
47: while (iter.hasNext()) {
48: T elem = iter.next();
49: if (set2.contains(elem)) {
50: // => present in set1 and in set2
51: both.add(elem);
52: }
53: }
54:
55: return both;
56: }
57:
58: /** @return the set of the elements of a not present in b
59: */
60: public final static <T> Set<T> notIn(final Set<T> a, final Set<T> b) {
61: final Set<T> notInB = new HashSet<T>();
62: final Iterator<T> iter = a.iterator();
63: while (iter.hasNext()) {
64: T elem = iter.next();
65: if (!b.contains(elem)) {
66: notInB.add(elem);
67: }
68: }
69: return notInB;
70: }
71:
72: public final static <T> boolean sameElements(final Set<T> a,
73: final Set<T> b) {
74: if (a.size() != b.size())
75: return false;
76:
77: Iterator<T> iter = a.iterator();
78: while (iter.hasNext()) {
79: T elem = iter.next();
80: if (!b.contains(elem))
81: return false;
82: }
83:
84: iter = b.iterator();
85: while (iter.hasNext()) {
86: T elem = iter.next();
87: if (!a.contains(elem))
88: return false;
89: }
90:
91: // same
92: return true;
93: }
94:
95: }
|