Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if Object inside List of List is empty or null?

I have something like List<List<UsersDetails>> userList. If I debug to see its value it's giving [[]] i.e., List<UsersDetails> is empty and List<List<UsersDetails>> is also empty. Is there a way to check if List<UsersDetails> is empty without iteration?

I tried userList.sizeOf, userList.empty() functions and userList==null operator but all are giving false.

like image 418
shrikant.sharma Avatar asked Oct 19 '25 10:10

shrikant.sharma


2 Answers

If you want to check each element in the "outer" list you have to iterate over it somehow. Java 8's streams would hide this from you, though, and provide a slightly cleaner syntax:

boolean allEmpty = userList.stream().allMatch(l -> l == null || l.empty());
like image 78
Mureinik Avatar answered Oct 22 '25 00:10

Mureinik


There is not. There is:

if (userList.isEmpty() || userList.get(0).isEmpty()) { ... }

But mostly if the notion: "This a list of lists where the list of lists contains 1 list, but that list is empty" is something you should consider as 'empty', you're using the wrong datastructure. You haven't explained what you are modelling with this List<List<UsersDetails>> but perhaps if you elaborate on that, some other data type in java.* or perhaps guava would be far more suitable. For example, maybe a Map<Integer, UsersDetail> is a better match here (mapping a user's ID to their details).

like image 41
rzwitserloot Avatar answered Oct 22 '25 01:10

rzwitserloot