Skip to content

Commit 7dd04b7

Browse files
committed
Add efficient RDD.isEmpty()
1 parent 1a200a3 commit 7dd04b7

File tree

2 files changed

+13
-0
lines changed

2 files changed

+13
-0
lines changed

core/src/main/scala/org/apache/spark/rdd/RDD.scala

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1175,6 +1175,12 @@ abstract class RDD[T: ClassTag](
11751175
* */
11761176
def min()(implicit ord: Ordering[T]): T = this.reduce(ord.min)
11771177

1178+
/**
1179+
* @return true if and only if the RDD contains no elements at all. Note that an RDD
1180+
* may be empty even when it has at least 1 partition.
1181+
*/
1182+
def isEmpty(): Boolean = partitions.length == 0 || take(1).length == 0
1183+
11781184
/**
11791185
* Save this RDD as a text file, using string representations of elements.
11801186
*/

core/src/test/scala/org/apache/spark/rdd/RDDSuite.scala

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@ class RDDSuite extends FunSuite with SharedSparkContext {
5252
assert(nums.glom().map(_.toList).collect().toList === List(List(1, 2), List(3, 4)))
5353
assert(nums.collect({ case i if i >= 3 => i.toString }).collect().toList === List("3", "4"))
5454
assert(nums.keyBy(_.toString).collect().toList === List(("1", 1), ("2", 2), ("3", 3), ("4", 4)))
55+
assert(!nums.isEmpty())
5556
assert(nums.max() === 4)
5657
assert(nums.min() === 1)
5758
val partitionSums = nums.mapPartitions(iter => Iterator(iter.reduceLeft(_ + _)))
@@ -545,6 +546,12 @@ class RDDSuite extends FunSuite with SharedSparkContext {
545546
assert(sortedTopK === nums.sorted(ord).take(5))
546547
}
547548

549+
test("isEmpty") {
550+
assert(sc.emptyRDD.isEmpty())
551+
assert(sc.parallelize(Seq[Int]()).isEmpty())
552+
assert(!sc.parallelize(Seq(1)).isEmpty())
553+
}
554+
548555
test("sample preserves partitioner") {
549556
val partitioner = new HashPartitioner(2)
550557
val rdd = sc.parallelize(Seq((0, 1), (2, 3))).partitionBy(partitioner)

0 commit comments

Comments
 (0)