Empty collection exception java

Checking if a collection is empty in Java: which is the best method?

My arch tells me that the former is better than latter. But I think the latter is better. Can anyone please clarify it?

collection interface provide isEmpty() method for empty check.both ways are better u can go with any one as per choice.

I think personal flavor has a way in this. CollectionUtils does 2 things in one call so it is easier for you as a developer. The latter gives you as a developer a little more work however you do save the computer a push of the collection ref on the stack and the whole stack work around it. Performance-wise, the latter will be slightly faster. Not that you’ll notice.

Hi there. am I the only one seeing this as a matter of legibility? The first one is obviously better for making the code way more legible. Which sentence makes you think less when reading that, the resolution of two operations combined with an and or simply reading isNotEmpty ?? We can talk long about the performance benefits of the latter, but as a matter of error proneness, the former is much more robust.

13 Answers 13

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 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.

Источник

Java Guides

In this short article, we will discuss how to check if the collection is empty or null in Java.

Let’s create a standard utility method to check if the collection is empty or null in Java.

Check if Collection is Empty or Null in Java — Utility Methods

  1. isEmptyOrNull(Collection collection) — Return true if the supplied Collection is null or empty. Otherwise, return false.
  2. isNotEmptyOrNull(Collection collection) — Return true if the supplied Collection is not null or not empty. Otherwise, return false.

1. isEmptyOrNull(Collection collection)

public static boolean isEmptyOrNull(Collection  ? > collection) < return (collection == null || collection.isEmpty()); >

2. isNotEmptyOrNull(Collection collection)

public static boolean isNotEmptyOrNull(Collection  ? > collection) < return !isEmptyOrNull(collection); >

Complete Example

package net.javaguides.lang; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; public class CollectionNullOrEmptyExample < public static void main(String[] args) < // return true if collection is null or empty System.out.println(isEmptyOrNull(null)); System.out.println(isEmptyOrNull(new ArrayList < >())); System.out.println(isEmptyOrNull(new LinkedList < >())); System.out.println(isEmptyOrNull(new HashSet < >())); // return false if collection is not empty or null System.out.println(isNotEmptyOrNull(new ArrayList < >())); System.out.println(isNotEmptyOrNull(new LinkedList < >())); System.out.println(isNotEmptyOrNull(new HashSet < >())); // return false if collection is not empty or null List  String > list = new ArrayList < String > (); list.add("ABC"); System.out.println(isNotEmptyOrNull(list)); List  String > list1 = new LinkedList < >(); list1.add("ABC"); System.out.println(isNotEmptyOrNull(list1)); Set  String > set = new HashSet < String > (); set.add("ABC"); System.out.println(isNotEmptyOrNull(set)); > public static boolean isEmptyOrNull(Collection collection) < return (collection == null || collection.isEmpty()); > public static boolean isNotEmptyOrNull(Collection collection) < return !isEmptyOrNull(collection); > >
true true true true false false false true true true
  • Check if Map is Null or Empty in Java
  • 18 Useful Collections Utility Methods
  • Java Custom CollectionUtils Class
  • 27 Useful String Utility Methods
  • Executors Utility Class in Java
  • java.util.Arrays Class
  • Java String Utility Class
  • java.util.Collections Class
  • Top Reflection Utility Methods
  • Java Reflection Utility Class
  • Java File Utility Class
  • Java Zip Utility Class
  • Java 8 Date Utility Class
  • Top File Utility Methods
  • Java LinkedHashMap Example
  • Java HashSet Example
  • Java LinkedList Example
  • Java ArrayList Example
  • Java Comparator Interface Example
  • Java Comparable Interface Example
  • Java IdentityHashMap Example
  • Java WeakHashMap Example
  • Java EnumMap Example
  • Java CopyOnWriteArraySet Example
  • Java EnumSet Class Example
  • Guide to Java 8 forEach Method
  • Different Ways to Iterate over a List in Java [Snippet]
  • Different Ways to Iterate over a Set in Java [Snippet]
  • Different Ways to Iterate over a Map in Java [Snippet]
  • Iterate over TreeSet in Java Example
  • Iterate over LinkedHashSet in Java Example
  • Remove First and Last Elements of LinkedList in Java
  • Iterate over LinkedList using an Iterator in Java
  • Search an Element in an ArrayList in Java
  • Iterate over ArrayList using Iterator in Java
  • Remove Element from HashSet in Java
  • Iterating over a HashSet using Iterator
  • How To Remove Duplicate Elements From ArrayList In Java?
  • Different Ways to Iterate over List, Set, and Map in Java

Источник

How to check if Collection is not empty using java Stream

I am new to Java 8. I am not able to understand what is wrong in the following piece of code. The idea is to sent Collection if its not empty. But if the collection is empty than sent HttpStatus.NOT_FOUND Entity response.

@RequestMapping(value = "/find/pks", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity> getUsers(@RequestBody final Collection pks) < return StreamSupport.stream(userRepository.findAll(pks).spliterator(), false) .map(list ->new ResponseEntity<>(list , HttpStatus.OK)) .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND)); > 
Iterable findAll(Iterable pks); 

Stream.map() returns a Stream, and a Stream doesn’t have an orElse() method. You’re making your own life complicated by returning an Iterable. Why don’t you return a List or a Set, or even a Collection, and use isEmpty()? BTW, what you’re mapping is not a list, it’s a user. If you really want to keep using Iterable, use iterable.iterator().hasNext() to see if it’s empty or not.

Then use iterable.iterator().hasNext() to see if it’s empty or not. But that said, I wouldn’t return a 404 in such a case. simply return an 200 with an empty list. 404 is for an unknown resource you try to get. You’re searching for resources here, and not finding anything is a valid result.

3 Answers 3

You are mixing two things up. The first task is to convert the Iterable to a Collection which you can indeed solve using the Stream API:

Collection list= StreamSupport.stream(userRepository.findAll(pks).spliterator(), false) .collect(Collectors.toList()); 

Note that this stream is a stream of User s, not a stream of lists. Therefore you can’t map a list to something else with this stream. The map operation will map each element of the stream to a new element.

Then you can use this list to create the ResponseEntity

return list.isEmpty()? new ResponseEntity<>(HttpStatus.NOT_FOUND): new ResponseEntity<>(list, HttpStatus.OK); 

You can combine these steps by creating a Collector performing this steps though this does not provide any advantage, it’s only a matter of style:

ResponseEntity responseEntity= StreamSupport.stream(userRepository.findAll(pks).spliterator(), false) .collect(Collectors.collectingAndThen(Collectors.toList(), list -> list.isEmpty()? new ResponseEntity<>(HttpStatus.NOT_FOUND): new ResponseEntity<>(list, HttpStatus.OK) )); 

Источник

which exception to throw if list is empty in java?

I am runing this code inside a batch, I want to throw some exception that will stop the batch execution.

5 Answers 5

Signals that a method has been invoked at an illegal or inappropriate time.

Basically your object is not in a valid state for run to be called.

I wouldn’t create your own exception for this unless you expect it to be deliberately caught elsewhere. It sounds like this would only occur due to a programming error rather than an unexpected situation. in which case an unchecked exception is appropriate, and IllegalStateException describes the general nature of the problem quite clearly.

You can put a detailed cause within the message of the exception (explaining that the «illegal state» was that the list was empty).

I suggest you try to avoid creating a separate exception type for every little thing that can go wrong — unless you’re catching these exceptions separately, having different types doesn’t help; it only adds to the clutter. An exception which is of the right broad type but has a useful message provides just as much benefit without as much cognitive overhead.

Note that you can’t use a checked exception if you’re implementing Runnable.run anyway, as that isn’t declared to throw any checked exceptions. You’d have to wrap it in an unchecked exception (e.g. RuntimeException ) at which point there’s even less benefit.

Источник

Best practice to validate null and empty collection in Java

I want to verify whether a collection is empty and null . Could anyone please let me know the best practice. Currently, I am checking as below:

if (null == sampleMap || sampleMap.isEmpty()) < // do something >else < // do something else >

Aside from anything else, think about why you use null == sampleMap rather than sampleMap == null . Most people find the latter more readable — the former is a holdover from other languages.

By the way, null collection is bad. If possible, make it empty collection instead. See Effective Java: Item 43 — Return empty arrays or collections, not nulls.

@JonSkeet people use null == sampleMap in case they write = instead of ==. if you use sampleMap == null, when you forget one =, it becomes sampleMap = null, which will not raise error thus writing it the other way helps the developer see it

@UriLoya: If you write if (null = sampleMap) in Java you’ll get a compilation error. That’s precisely the point of my first comment. The «reason» for it is language-specific, but has been propagated to other languages despite the readability penalty because people haven’t considered why they’re doing that.

You can use CollectionUtils class which is present in org.apache.commons.collections4.CollectionUtils package. There have many utility methods to find empty or null.

9 Answers 9

If you use the Apache Commons Collections library in your project, you may use the CollectionUtils.isEmpty(. ) and MapUtils.isEmpty(. ) methods which respectively check if a collection or a map is empty or null (i.e. they are «null-safe»).

The code behind these methods is more or less what user @icza has written in his answer.

Regardless of what you do, remember that the less code you write, the less code you need to test as the complexity of your code decreases.

That is the best way to check it. You could write a helper method to do it:

public static boolean isNullOrEmpty( final Collection < ? >c ) < return c == null || c.isEmpty(); >public static boolean isNullOrEmpty( final Map < ?, ? >m )

I don’t understand if m is null then .isEmpty() will cause NullPointerException rigth? otherwise, if the left side (m==null) is true then the remaining will not be checked

@ismail The || operator is a short-circuit operator, meaning if the left operand is true , it won’t evaluate the right operand. So if m == null , then m.isEmpty() will not be called (not needed, the result is true ).

Источник

Читайте также:  Oracle php and apache
Оцените статью