111

I see that Guava has isNullOrEmpty utility method for Strings

Strings.isNullOrEmpty(str)

Do we have anything similar for Lists? Something like

Lists.isNullOrEmpty(list)

which should be equivalent to

list == null || list.isEmpty()

Also, do we have anything similar for Arrays? Something like

Arrays.isNullOrEmpty(arr)

which should be equivalent to

arr == null || arr.length == 0
Paŭlo Ebermann
  • 73,284
  • 20
  • 146
  • 210
Ramesh
  • 3,841
  • 5
  • 22
  • 28

7 Answers7

152

No, this method does not exist in Guava and is in fact in our "idea graveyard."

We don't believe that "is null or empty" is a question you ever really want to be asking about a collection.

If a collection might be null, and null should be treated the same as empty, then get all that ambiguity out of the way up front, like this:

Set<Foo> foos = NaughtyClass.getFoos();
if (foos == null) {
  foos = ImmutableSet.of();
}

or like this (if you prefer):

Set<Foo> foos = MoreObjects.firstNonNull(
    NaughtyClass.getFoos(), ImmutableSet.<Foo>of());

After that, you can just use .isEmpty() like normal. Do this immediately upon calling the naughty API and you've put the weirdness behind you, instead of letting it continue on indefinitely.

And if the "null which really means empty collection" is not being returned to you, but passed to you, your job is easy: just let a NullPointerException be thrown, and make that caller shape up.

Kevin Bourrillion
  • 40,336
  • 12
  • 74
  • 87
  • 7
    What if some framework is setting it field to null and you can't control it (spring framework when on binding to list) although you explicitly set and use empty list in the object. – OMax Mar 11 '12 at 19:02
  • 15
    My answer is the same: try to remove the ambiguity by normalizing `null` to an empty collection as soon as you can. If you just can't, then okay, you might be one of the <1% of users who really want to write their own trivial isNullOrEmpty(Collection) helper. – Kevin Bourrillion Mar 14 '12 at 17:25
  • 8
    (or skip the helper and just write `if (collection == null || collection.isEmpty())` in those cases where you need it! Is that so bad?) – Kevin Bourrillion Aug 28 '12 at 17:43
  • 14
    This is an opinionated answer that doesn't actually address the question at all. It also goes against defensive programming principles. – Neovibrant Oct 16 '13 at 16:23
  • 12
    @Neovibrant since the question is about the capabilities of the Guava library, and the answer is from one of the lead developer of Guava, the answer is kinda implied: "No, Guava doesn't have that". The answer may be improved by starting with that statement though :) – Grundlefleck Nov 10 '13 at 21:50
  • So you should start to believe that it is sometimes useful to ask this question. My proposal is to write some validator which is considering if there is any element in collection for some external data. Writing code like you've proposed will be just ridiculous in validators like this. – panurg Oct 16 '14 at 10:27
  • 4
    @Grundlefleck okay, did that. – Kevin Bourrillion Nov 02 '14 at 16:39
  • 2
    It'd be awesome if Guava added a Lists.nullToEmpty() method for consistency. – Stephen Kidson Nov 29 '14 at 01:32
  • 1
    ironic because Google's own Drive SDK's love to return null in place of empty collections, whenever it can... I was dealing with this fact when I searched for a Guava `isNullOrEmpty` for collections – Don Cheadle Apr 16 '15 at 18:16
  • 7
    Also, couldn't the exact same argument be made for null Strings? Why create Strings.isNullOrEmpty() but not Collections. equivalent? – Don Cheadle Apr 16 '15 at 18:18
  • I think "isNotEmpty" would be useful for readability because in "!sdadsifai.dsaoifh().adsfoish().isEmpty()" the negation symbol and isEmpty() are visually so far apart it makes the code easy to misunderstand. – tkruse Jan 22 '16 at 16:25
  • @user2986984 - the problem is there's no positive synonym to 'non empty'. Personally I've grown to like the word 'laden', but that's hardly common. – aaaaaa May 02 '17 at 12:28
  • How is normalizing null to an empty collection different from normalizing a null String to an empty String? I second @DonCheadle – andrei.serea Jan 14 '20 at 08:44
37

One thing you will tend to find throughout Guava is that they tend to be very antagonistic toward nulls. The authors want to discourage you from using null as much as you probably do, and providing utility methods to make it easier to use null would be counterproductive against this end.

If you want to use Guava's paradigm, consider if the source of this collection (or array) really ought to optionally return null. If not, consider marking it @NonNull and return empty collections instead of null. Or as a parameter to a function that is expecting no null-valued lists, consider using Preconditions.checkNotNull, which throws an exception if a null is (unexpectedly) passed in.

If null really is legitimate, list == null || list.isEmpty() is not that hard.

Ray
  • 4,829
  • 4
  • 28
  • 55
32

There's a CollectionUtils.isEmpty() in commons-collections.

Grzegorz Rożniecki
  • 27,415
  • 11
  • 90
  • 112
Steven Schlansker
  • 37,580
  • 14
  • 81
  • 100
  • 1
    Unfortunately, it seems to have been removed in more recent versions. See org.apache.commons.collections15.CollectionUtils. – spaaarky21 May 15 '12 at 20:38
  • 1
    Looking at the Javadoc from apache.commons.collection the methods isEmpty() and isNotEmpty() still exist in the latest version. collections15.CollectionUtils seems like an independent project trying to provide generic support. – proko Aug 13 '12 at 13:18
  • 1
    CollectionUtils.isEmpty() is useful when working with legacy apps, when you cannot change the up front code. – Jerome Dalbert Oct 09 '12 at 09:58
  • 1
    we know this, but one was asking about guava not about apache commons. – To Kra Dec 03 '15 at 09:27
11

Spring Framework has specialized util class called CollectionUtils. And the method you are looking for is: org.springframework.util.CollectionUtils.isEmpty. It returns true for null and empty collections.

And for arrays there is org.springframework.util.ObjectUtils.isEmpty method which behaves pretty the same.

Lukasz
  • 7,572
  • 4
  • 41
  • 50
  • 6
    Although it's probably safe to use it, this class is marked with "Mainly for internal use within the framework" comment. This means its interface might change on a Spring upgrade and you will have to do additional work to make it work again. – Mike Minicki Dec 03 '13 at 01:00
3

Apache CollectionUtils 4 has a method CollectionUtils.emptyIfNull() that returns a empty list if the collection is null. This is very useful in a foreach loop, so you dont need to do a null check before iterating

Jeffrey
  • 1,068
  • 2
  • 15
  • 25
1

My solution is : MoreObjects.firstNonNull(list, Collections. emptyList())

I am using Guava MoreObjects with JDK Collections.

 @Test
public void listnull() {
List<String> list = null;

for (String str : MoreObjects.firstNonNull(list, Collections.<String> emptyList())) {
    System.out.println(str);
}

list = new ArrayList<String>();
list.add("http://stackoverflow.com/");

for (String str : MoreObjects.firstNonNull(list, Collections.<String> emptyList())) {
    System.out.println(str);
}
}
jeton
  • 841
  • 12
  • 15
  • 1
    This is exactly what's suggested in the [top answer](http://stackoverflow.com/a/6921270/113632), except you don't use an `ImmutableList`. – dimo414 May 18 '15 at 20:41
  • I think negative because one wanted simple & quick solution like apache commons methods inNotEmpty ... – To Kra Dec 03 '15 at 09:28
  • Help Center > Privileges > Vote Down When should I vote down? Use your downvotes whenever you encounter an egregiously sloppy, no-effort-expended post, or an answer that is clearly and perhaps dangerously incorrect. You have a limited number of votes per day, and answer down-votes cost you a tiny bit of reputation on top of that; use them wisely.http://stackoverflow.com/help/privileges/vote-down – jeton Dec 11 '15 at 18:01
  • Do you think my answer is "egregiously sloppy, no-effort-expended post, or an answer that is clearly and perhaps dangerously incorrect"? If not, why are you negative voting? – jeton Dec 11 '15 at 18:02
0

Look at Appache Collections CollectionUtils.isEmpty() returns true if collection is null or empty