Any faster alternatives to isEmpty method for Set? [duplicate] - java

I have two ways of checking if a List is empty or not
if (CollectionUtils.isNotEmpty(listName))
and
if (listName != null && listName.size() != 0)
My arch tells me that the former is better than latter. But I think the latter is better.
Can anyone please clarify it?

You should absolutely use isEmpty(). Computing the size() of an arbitrary list could be expensive. Even validating whether it has any elements can be expensive, of course, but there's no optimization for size() which can't also make isEmpty() faster, whereas the reverse is not the case.
For example, suppose you had a linked list structure which didn't cache the size (whereas LinkedList<E> does). Then size() would become an O(N) operation, whereas isEmpty() would still be O(1).
Additionally of course, using isEmpty() states what you're actually interested in more clearly.

CollectionUtils.isNotEmpty checks if your collection is not null and not empty. This is better comparing to double check but only if you have this Apache library in your project. If you don't then use:
if(list != null && !list.isEmpty())

Unless you are already using CollectionUtils I would go for List.isEmpty(), less dependencies.
Performance wise CollectionUtils will be a tad slower. Because it basically follows the same logic but has additional overhead.
So it would be readability vs. performance vs. dependencies. Not much of a big difference though.

if (CollectionUtils.isNotEmpty(listName))
Is the same as:
if(listName != null && !listName.isEmpty())
In first approach listName can be null and null pointer exception will not be thrown. In second approach you have to check for null manually. First approach is better because it requires less work from you. Using .size() != 0 is something unnecessary at all, also i learned that it is slower than using .isEmpty()

If you have the Apache common utilities in your project rather use the first one. Because its shorter and does exactly the same as the latter one. There won't be any difference between both methods but how it looks inside the source code.
Also a empty check using
listName.size() != 0
Is discouraged because all collection implementations have the
listName.isEmpty()
function that does exactly the same.
So all in all, if you have the Apache common utils in your classpath anyway, use
if (CollectionUtils.isNotEmpty(listName))
in any other case use
if(listName != null && listName.isEmpty())
You will not notice any performance difference. Both lines do exactly the same.

Apache Commons' CollectionUtils.isNotEmpty(Collection) is a NULL-SAFE check
Returns TRUE is the Collection/List is not-empty and not-null
Returns FALSE if the Collection is Null
Example:
List<String> properties = new ArrayList();
...
if (CollectionUtils.isNotEmpty(properties)) {
// process the list
} else {
// list is null or empty
}
Refer:
https://commons.apache.org/proper/commons-collections/apidocs/org/apache/commons/collections4/CollectionUtils.html#isNotEmpty(java.util.Collection)

isEmpty()
Returns true if this list contains no elements.
http://docs.oracle.com/javase/1.4.2/docs/api/java/util/List.html

A good example of where this matters in practice is the ConcurrentSkipListSet implementation in the JDK, which states:
Beware that, unlike in most collections, the size method is not a constant-time operation.
This is a clear case where isEmpty() is much more efficient than checking whether size()==0.
You can see why, intuitively, this might be the case in some collections. If it's the sort of structure where you have to traverse the whole thing to count the elements, then if all you want to know is whether it's empty, you can stop as soon as you've found the first one.

Use CollectionUtils.isEmpty(Collection coll)
Null-safe check if the specified collection is empty.
Null returns true.
Parameters:
coll - the collection to check, may be null
Returns:
true if empty or null

The org.apache.commons.collections4.CollectionUtils isEmpty() method is used to check any collections(List, Set, etc.) are empty or not. It checks for null as well as size of collections. The CollectionUtils isEmpty() is a static method, which accepts Collection as a parameter.

I would use the first one. It is clear to see right away what it does. I dont think the null check is necessary here.

table.column = ANY(ARRAY[ :canEmptyArrayParameter ]::BIGINT[])
It helps me to check empty parameter of array
this parameter can be Collections.emptyList();

To Check collection is empty, you can use method: .count(). Example:
DBCollection collection = mMongoOperation.getCollection("sequence");
if(collection.count() == 0) {
SequenceId sequenceId = new SequenceId("id", 0);
mMongoOperation.save(sequenceId);
}

Related

Check that array is empty, but not null

I have an array of objects (Object[] array), and I want to check whether it is empty, but fail fast if it is null with NPE or any other exception.
I know that I can do the following check
array.length == 0
but e.g. in case of String or collections it is not recommended practice, IntelliJ even has inspection for that:
Reports any .size() or .length() comparisons with a 0 literal which can be replaced with a call to .isEmpty().
Is there any replacement for .isEmpty() for arrays?
There is ArrayUtils.html#isEmpty(java.lang.Object[]), but it also checks for null, while I'd like to avoid that.
Because .size() is method, its implementation is hidden. And you can't be sure that this method optimized (there's a possibility, that some collections, for example, enumerate items every time you call .size() method). That is why computing the .size() of collection could be expensive. In the same time, .isEmpty() can checks just is there at least one item in collection, and return result.
But .length is just a field. It does nothing, just returns a value. There are no calculations. This field just stores the length of array with fixed size.
I believe that .size() and .length are totally different things and in this case they can not be compared, as well as collections and arrays.
The easiest way would to be to write such a method yourself. It would be fairly trivial. Something like the following
public boolean isArrayEmpty(Object[] array) {
if (array == null) {
//Throw nullpointer exception
//An easy of method of doing this would be accessing any array field (for example: array.length)
}
return (ArrayUtils.isEmpty(array));
}
That being said, there's very little reason why array.length == 0 would be harmful. It's the simplest, cleanest way to do this and does exactly what you want. Most likely part of the reason for ArrayUtils.isEmpty is to allow easy testing of whether or not a array is empty or null, a relatively common need, but you don't want to do that.

How to use empty list when we have an empty list anyways

This question is a bit hard to explain so please look at the increasingPath function in the code here. Now assuming the path does not exist, and arraylist pointPath with 0 size is returned.
However I have read that we must use Collections.emptyList, but how do I use it in this scenario, when I already have a probably empty list called pointPath ? If not to use Collections.emptyList then when to use it ?
I think what you're supposed to do is use Collections.EmptyList for comparisons and returning.
for example:
if (pointPath.equals(Collections.emptyList()){
return Collections.emptyList();
}
I don't think it changes how your program will execute, but it makes the code readable and self-documenting.
Simply check
if (pointPath.isEmpty()){
return Collections.emptyList();
}
The only difference from actually returning a your list that is accidentally empty is that Collections.emptyList() is immutable list. If that is not of any value to you, I'd return your real list. That way there is less code to read.

When to return empty collections and when not too?

This question regards to the function public List inorderTraversal ().
Assume a case the root is null, the returned List is empty, ie size = 0. I am confused now since this is same as Collections.emptyList(). When should we use Collections.emptyList ? Is this inorderTraversal right place to use it instead of list with size 0 ?
public static void main(String[] args) {
List l = Collections.emptyList();
l.clear(); // No NPE
List p = null;
p.clear(); // NPE
}
So, prefer returning emptyList rather than returning null..
Collections.emptyList is a very useful means of storing a reference to an empty list (which I guess is kind of obvious).
The benefit of using it is that it's only going to occupy the memory required for a single list. Using it saves you the memory that you would use if you had multiple empty lists lying around. Also, as it's static, this List instance will always exist, whether you use it once, a thousand times or not at all.
You should use it when you wish to return a "static" list containing no objects. I use the term "static" here to indicate that the list is empty and will not be populated by any means. For example, if you have a data-access object and do a database-retrieval that yields no objects then your accessor should return a Collections#emptyList
However, if you have a list that is being used dynamically (and becomes empty as part of this), such as to back a data-structure like your own List implementation, then you should not use it as you need to keep a reference to the active list.
Additionally, if (as you should) you return defensive copies of internal arrays, then you will be able to use Collections#emptyList for when the internal list is empty.
I would return an empty collection whenever it makes sense to do so. If you need to distinguish between an empty collection and "uninitialised" or some null state, then you can return null.
You can check the size of a resulting List just before return. If the size is 0, you can return Collections.emptyList(), so your empty ArrayList will become orphaned, and will be garbage collected.
Empty lists IMO a preferable to null, since they cat prevent NullPointerException
Put simply: yes. This way, if root is null you can avoid creating ArrayList (and consuming memory unnecessarily) .
Although this is not what you ask about, but generally returning empty collection is preferred over returning null - it prevents many NPEs.
Please note that Collections.emptyList() returns an immutable list, which means that adding to it, or removing from it will fail.
http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#emptyList()

Best way to check collections not null & null conditions

we use collections like ArrayList,hashmap & many more.
Number of times we have check condition like whether list is null or not.
We have many ways to chek whether our collection is null or not.
Different ways.
1. if(list==null)
2. if(list.size()==0)
3. if(list.isEmpty())
Also sometimes we also need to check whether list is not null , so we normally check it by these ways
1. if(list!=null)
2. if(list.size()>0)
3. if(!list.isEmpty())
Which is best condition or do we need to make some combination of
these considering performance of program execution?
Best combination would be
if(list!=null && !list.isEmpty()){
//Yeah ,do something
}
One for null check, and then any thing there or not check
1. if(list!=null)
You should make sure that is never the case!!
Read Effective Java 2nd Edition by Joshua Bloch
Item 43: Return empty arrays or collections, not nulls
[...] In summary, there is no reason ever to return null from an array- or
collection-valued method instead of returning an empty array or
collection. The null-return idiom is likely a holdover from the C
programming language, in which array lengths are returned separately
from actual arrays. In C, there is no advantage to allocating an array
if zero is returned as the length.
In short, let your methods return Collections.emptyList() instead of null and you've got one thing less to worry about.
2. if(list.size()>0)
3. if(!list.isEmpty())
That depends. For a simple collection such as ArrayList, they are equivalent. But what if your Collection is actually a live view of a Database query? Calling size() might me a very expensive operation, whereas isEmpty() will always be O(1). I'd say use isEmpty().
Also see Jon Skeet's answer here: https://stackoverflow.com/a/11152624/342852
In Java8 you can use Optional to handle null cases properly. For example, both lists animalsNull and animalWithNullElements would be properly handled by the function filterList:
List<String> animalsNull = null;
List<String> animalWithNullElements = new ArrayList<String>();
animalWithNullElements.add(0, null);
animalWithNullElements.add(1, "Guybrush Threepwood");
animalWithNullElements.add(2, null);
private static List<String> filterList(List<String> animals) {
return Optional.ofNullable(animals)
.orElseGet(Collections::emptyList)
.stream()
.filter(Objects::nonNull)
.collect(Collectors.toList());
}
It really depends on what you want to do. If you want to be sure that a list exist AND has some elements then you would use
if (list != null && !list.isEmpty())
If I may give some advice, while returning collections, return by default an empty collection. That way you will avoid nulls.
Number of times we have check condition like whether list is null or not.
For a start, a null collection and an empty collection are different things. If you need to test if a collection is null you need a different test to if you are trying to test if the collection is empty.
Secondly, if a collection could be either null or empty (and they "mean" the same thing, per your application design) then you have a problem in your design. You should most likely represent ... whatever it is you are trying to represent ... one way, and not either / both ways.
Thirdly, it is generally best to use an empty collection rather than a null, because you can treat an empty and non-empty collection uniformly. By contrast, a null always needs to be handled as a special case. (And if you forget to handle the null case, then you've got a potential for NullPointerExceptions.)
Having said that ...
Which is best condition or do we need to make some combination of these considering performance of program execution?
If you really need to deal with the case of a null, then you've no choice but to test for null.
For isEmpty() versus size() == 0:
the two predicates should give the same answer (unless you have an infinite lazy collection ...), but
in some cases isEmpty() could be faster, at least in theory.
The latter depends on the implementation of the collection type: specifically, on whether the size() method needs to count the collection elements. (I don't think that any of the standard collection classes have this property, but that's not to say that you won't find some class that does ...)
So the optimal predicate is most likely either:
c != null && !c.isEmpty()
or
!c.isEmpty()
depending on whether you (really) need to cater for nulls.
And the obvious corollary is that your application is likely to be more efficient ... as well as simpler and more robust ... if you don't use null to represent empty collections. (If you need immutable empty collection objects, you can get them for free from methods / statics defined by the Collections class.)
There is a useful util class called CollectionUtils from Apache commons-collections bundle. With using it the code will look like:
if(CollectionUtils.isEmpty(collection))
It looks nice and under the hood it has the same invocation:
public static boolean isEmpty(Collection coll) {
return coll == null || coll.isEmpty();
}
null means list is initialized with null. null list size or isEmpty will throw NullPointerException. But, not null list can be empty or size==0
(list!=null) != (list.size()==0)
size==0 and isEmpty is equivalent.
(list.size()==0) == list.isEmpty()
There can be multiple approaches to handle this:
1: If code makes sure that collection cannot be null by initializing it either in constructor or as field initializaiton then caller need not to ideally check for null everywhere. Only isEmpty check should suffice:
private List<Integer> numbers = new ArrayList<Integer>(); //or in constructor
// caller can then safely use
if(numbers.isEmpty)
2: Alternatively write a utility method to have null and empty check, no need for size check as it already happens inside isEmpty call. Use this utility method elsewhere in code.
public static boolean empty(Collection<?> col) {
return col == null || col.isEmpty();
}
It depends on your program structure. For example, I have a helper class called ArrayUtils, in which I have an API that looks like this:
public static <E> boolean isEmpty(final Collection<E> collection)
{
return collection == null || collection.isEmpty();
}
I use this one when I know that I may get a null list, but when I'm absolutely sure it's not null, I use only if ( collection.isEmpty ). Improves code readability, too.
collection.size() > 1 is redundant, because you have the other APIs at your disposal.
If it you are owner of the codebase, I would avoid using such logic at all.
Instead try to follow the model when your collection supplier can't return null but has a reference to Collections.emptyXXX or just regular empty container empty.
You can do it with two predicates as below :
public static final Predicate<String> NULL_OR_EMPTY = (in) -> null == in || "".equals(in);
public static final Predicate<List<String>> STRING_LIST_NULL_OR_EMPTY = (strList) -> strList.stream().filter(NULL_OR_EMPTY).collect(Collectors.toList()).size() > 0;

Use of array of zero length

For example we can construct such an array like this:
new ElementType[0];
I seen such a construct, but I don't understand why this might be useful.
An example. Say, you have a function
public String[] getFileNames(String criteria) {
to get some filenames. Imagine that you don't find any filenames satisfying criteria. What do you return? You have 2 choices - either return null, or 0-sized array.
The variant with 0-sized array is better, because your caller doesn't need to check for NULL and can process the array in a consistent way - say, in a loop (which would be empty in this case).
There's a chapter on this in Effective Java, Item 27
It's easier to work with than null in many cases, where null is the obvious alternative.
Suppose you want to return an Iterable<String> containing (say) a list of relevant filenames... but there aren't any for some reason. You could return null to indicate that, but then the caller has to special-case that. Instead, if you return an empty collection, the caller can still use an enhanced for loop:
for (String file : getFiles())
So why use an empty array instead of an empty ArrayList or something similar? Arrays are a fixed size, so an empty array is effectively immutable. That means you can keep a single value and return it to whoever you like, knowing they can't possibly do anything with it. That can be very useful in some situations.
it is a replacement for null since you don't need to check for null before use it.
More formally it is a special case of special case design pattern (check also Null Object).
Another idiomatic use is collections toArray:
List<String> list = new ... ;
// fill the list
String[] array = list.toArray(new String[0]);

Categories