1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.giraph.utils;
20
21 import com.google.common.collect.Iterables;
22 import java.util.Collection;
23 import java.util.Iterator;
24 import java.util.concurrent.ConcurrentMap;
25 import org.apache.log4j.Logger;
26
27
28 public class CollectionUtils {
29
30 private static final Logger LOG = Logger.getLogger(CollectionUtils.class);
31
32
33 private CollectionUtils() { }
34
35
36
37
38
39
40
41
42
43
44
45
46
47 public static <K, V, C extends Collection<V>> C addConcurrent(K key,
48 C values, ConcurrentMap<K, C> map) {
49 C currentValues = map.get(key);
50 if (currentValues == null) {
51 currentValues = map.putIfAbsent(key, values);
52 if (currentValues == null) {
53 return values;
54 }
55 }
56 synchronized (currentValues) {
57 currentValues.addAll(values);
58 }
59 return currentValues;
60 }
61
62
63
64
65
66
67
68
69
70
71
72
73
74 public static <T> boolean isEqual(Iterable<T> first, Iterable<T> second) {
75
76
77
78
79 int firstSize = Iterables.size(first);
80 int secondSize = Iterables.size(second);
81 boolean[] usedSecondArray = new boolean[secondSize];
82 Iterator<T> firstIterator = first.iterator();
83 while (firstIterator.hasNext()) {
84 T firstValue = firstIterator.next();
85 boolean foundFirstValue = false;
86 Iterator<T> secondIterator = second.iterator();
87 for (int i = 0; i < usedSecondArray.length; ++i) {
88 T secondValue = secondIterator.next();
89 if (!usedSecondArray[i]) {
90 if (firstValue.equals(secondValue)) {
91 usedSecondArray[i] = true;
92 foundFirstValue = true;
93 break;
94 }
95 }
96 }
97
98 if (!foundFirstValue) {
99 LOG.error("isEqual: Couldn't find element from first (" + firstValue +
100 ") in second " + second + "(size=" + secondSize + ")");
101 return false;
102 }
103 }
104
105 Iterator<T> secondIterator = second.iterator();
106 for (int i = 0; i < usedSecondArray.length; ++i) {
107 T secondValue = secondIterator.next();
108 if (!usedSecondArray[i]) {
109 LOG.error("isEqual: Element " + secondValue + " (index " + i +
110 ") in second " + second + "(size=" + secondSize +
111 ") not found in " + first + " (size=" + firstSize + ")");
112 return false;
113 }
114 }
115
116 return true;
117 }
118 }