check null pointer before sorting and iterating