lapots
lapots

Reputation: 13395

Checking multiple lists for emptiness in Groovy

Let's say I've got three lists with objects

List<String> list1, list2, list3

What is the best way to do check whether any of them is not empty and do some action?

So far I came up with

if ([list1, list2, list3].any()) {
    // do some action
}

But is there a way to omit if block at all?

Upvotes: 3

Views: 6276

Answers (2)

Michael Easter
Michael Easter

Reputation: 24468

One objective part of your question is about omitting the if block. This answer pertains to that. I don't recommend this for production code, nor do I claim this is the best way, which is subjective.

Generally, if statements can be "hidden" by using maps. (The context is a new static method on List, via Groovy's meta-programming):

List.metaClass.static.ifNotEmpty = { List<String>... lists ->
    def resultMap = [:]

    resultMap[true] = { Closure c -> c.call() }
    resultMap[false] = { Closure c -> }

    return resultMap[lists.any()]
}

Here are example usages... See this Q&A to understand the unusual syntax of ({ })

List<String> list1, list2, list3

list1 = []
list2 = null
list3 = []
list3 << "HELLO"

List.ifNotEmpty(list1, list2, list3) ({ println "test 1" })

list1 = []
list2 = null
list3 = []

List.ifNotEmpty(list1, list2, list3) ({ println "should not see this" })

Upvotes: 0

AdamSkywalker
AdamSkywalker

Reputation: 11609

I don't think there can be anything better than

if (list1 || list2 || list3) {
}

You want some kind of NotEmptyPredicate(l1, l2, l3).ifMatch { println 'hi' }, but it does not exist in standard library. Creating one is not worth.

Upvotes: 2

Related Questions