3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[Groovy]Nullセーフ

Last updated at Posted at 2014-05-13

概要

nullが混じったIntegerのリストから合計数を求めるサンプル。
個人的にはパターン4が好き。

def list = [null, 1, 2, null, 3, 4, 5, null]

// パターン1
def globalCounter = 0
for(def i = 0; i < list.size(); i++) {
    if (list[i] != null) {
        globalCounter += list[i]
    }
}
assert 15 == globalCounter

// パターン2
assert 15 == list.inject(0) {x, y ->
    if (y != null) {
        x + y
    } else {
        x
    }
}

// パターン3
assert 15 == list.inject(0){x, y ->
    y != null ? x + y : x
}

// パターン4
assert 15 == list.findAll{it != null}.inject{x,y -> x+y}
3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?