Skip to content

Commit 6930e96

Browse files
committed
[SPARK-6512] add contains to OpenHashMap
Add `contains` to test whether a key exists in an OpenHashMap. rxin Author: Xiangrui Meng <[email protected]> Closes #5171 from mengxr/openhashmap-contains and squashes the following commits: d6e6f1f [Xiangrui Meng] add contains to primitivekeyopenhashmap 748a69b [Xiangrui Meng] add contains to OpenHashMap
1 parent 05c2214 commit 6930e96

File tree

4 files changed

+31
-0
lines changed

4 files changed

+31
-0
lines changed

core/src/main/scala/org/apache/spark/util/collection/OpenHashMap.scala

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,15 @@ class OpenHashMap[K : ClassTag, @specialized(Long, Int, Double) V: ClassTag](
5353

5454
override def size: Int = if (haveNullValue) _keySet.size + 1 else _keySet.size
5555

56+
/** Tests whether this map contains a binding for a key. */
57+
def contains(k: K): Boolean = {
58+
if (k == null) {
59+
haveNullValue
60+
} else {
61+
_keySet.getPos(k) != OpenHashSet.INVALID_POS
62+
}
63+
}
64+
5665
/** Get the value for a given key */
5766
def apply(k: K): V = {
5867
if (k == null) {

core/src/main/scala/org/apache/spark/util/collection/PrimitiveKeyOpenHashMap.scala

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,11 @@ class PrimitiveKeyOpenHashMap[@specialized(Long, Int) K: ClassTag,
4848

4949
override def size: Int = _keySet.size
5050

51+
/** Tests whether this map contains a binding for a key. */
52+
def contains(k: K): Boolean = {
53+
_keySet.getPos(k) != OpenHashSet.INVALID_POS
54+
}
55+
5156
/** Get the value for a given key */
5257
def apply(k: K): V = {
5358
val pos = _keySet.getPos(k)

core/src/test/scala/org/apache/spark/util/collection/OpenHashMapSuite.scala

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -176,4 +176,14 @@ class OpenHashMapSuite extends FunSuite with Matchers {
176176
assert(map(i.toString) === i.toString)
177177
}
178178
}
179+
180+
test("contains") {
181+
val map = new OpenHashMap[String, Int](2)
182+
map("a") = 1
183+
assert(map.contains("a"))
184+
assert(!map.contains("b"))
185+
assert(!map.contains(null))
186+
map(null) = 0
187+
assert(map.contains(null))
188+
}
179189
}

core/src/test/scala/org/apache/spark/util/collection/PrimitiveKeyOpenHashMapSuite.scala

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,4 +118,11 @@ class PrimitiveKeyOpenHashMapSuite extends FunSuite with Matchers {
118118
assert(map(i.toLong) === i.toString)
119119
}
120120
}
121+
122+
test("contains") {
123+
val map = new PrimitiveKeyOpenHashMap[Int, Int](1)
124+
map(0) = 0
125+
assert(map.contains(0))
126+
assert(!map.contains(1))
127+
}
121128
}

0 commit comments

Comments
 (0)