2

I am getting NoSuchElementException while using Collections.min, I have read other related questions too on the site, and learned that one gets this exception if the list or collection used is empty. But I have checked debugging the code, the list has values, still I am getting the exception.

public Date getNewDate(List<MyClass> list1){

    Comparator<MyClass> startDate = new Comparator<MyClass>() {
        @Override
        public int compare(MyClass date1, MyClass date2) {
            return date1.getStartDate().compareTo(date2.getStartDate());
        }
    };

    return Collections.min(list1, startDate).getStartDate();
}
Preeti Singh
  • 37
  • 3
  • 12

1 Answers1

4

Why would you need to read other related questions to learn this, when your first source of information, the javadoc, explicitly tells you so?

Quoting javadoc of Collections.min():

Throws NoSuchElementException if the collection is empty.

Ergo, your collection (list1) is empty.

If you don't believe it, try catching and enhancing the error message:

try {
    return Collections.min(list1, startDate).getStartDate();
} catch (NoSuchElementException e) {
    throw new RuntimeException("Got NoSuchElementException but list size is " +
                               list.size() + " (list is: " + list + ")", e);
}

Show us the full stack trace produced when you do this, to prove that the list is not empty when you get the exception.

This will also show us the content of the list, which is part of providing a Minimal, Complete, and Verifiable example.

Andreas
  • 154,647
  • 11
  • 152
  • 247