2

I am using Multimap from Guava as shown below since I can have same keys many times but with different values.

Multimap<Long, Plesk> map = ArrayListMultimap.create();
// populate data into map

// extract value from the above map
Collection<Plesk> plesk = map.get(id);

And now from the same multimap I am extracting a particular key value. Now how can I check whether plesk variable is null or not? After I print out my map variable, I see one entry as:

1100178=[null]

so plesk variable is getting value as [null] for id 1100178 and if I use below code to check for null and empty then it doesn't work:

if (CollectionUtils.isEmpty(plesk)) {
    // do stuff
}

What is the right way to check whether value of multimap is null or not?

user1234
  • 145
  • 1
  • 12
  • Did you try `if (plesk != null && CollectionUtils.isEmpty(plesk)) { // do stuff } else { //null or empty, do other stuff }` ? – LoneWanderer Mar 14 '17 at 23:55
  • isEmpty already check for null. – user1234 Mar 14 '17 at 23:56
  • 2
    But it's not null, it's a collection containing one null element. What are you trying to do? – shmosel Mar 14 '17 at 23:56
  • Possible duplicate of [Adding a key with an empty value to Guava Multimap](http://stackoverflow.com/questions/11587895/adding-a-key-with-an-empty-value-to-guava-multimap) – shmosel Mar 15 '17 at 00:11

2 Answers2

4

The result of Multimap.get(key) is never null. If there are no values associated with that key, it returns an empty Collection.

Your plesk collection appears to be a collection with a single element, and that single element is null.

ColinD
  • 108,630
  • 30
  • 201
  • 202
0

As others have already said, the result of multimap.get(key) is never null and returns an empty collection if there are no values associated.
From your question, I can understand that you want to check whether there is a value present or not and perform some action if there is no value found for a specific key.
I would do something like this:

Multimap<String, String> multimap = LinkedListMultimap.create();
multimap.put("Name", "SomeName");
multimap.put("ID", "");
multimap.put("City", "SomeCity");
Collection<String> contentsofID = multimap.get("ID");
if (contentsofID.toString().equals("[]")) {
    // This means that there is no value in it
    // Then perform what you want
}
Suhas
  • 106
  • 1
  • 2
  • 6