Home > OS >  java.util.NoSuchElementException when iterating the List
java.util.NoSuchElementException when iterating the List

Time:12-09

I am trying to iterate the list and check the max value to get that object.

Class One{
//properties
private int id;
private boolean isInsurance;
private List<FamilyAge> familyAge;
}
class FamilyAge{
private Long aId;
private String holder1;
private String holder2;
..
}

Above are the sample class objects iterating below.

    List<One> myList1 = getAllRequiredData();
        myList1.stream().forEach(list1 -> list1.getFamilyAge().stream()
                                     .max(Comparator.comparing(FamilyAge::getAId)).get()); 
         //java.util.NoSuchElementException: No value present

I want to filter or get only one object of FamilyAge which has max of aId. With the above iteration logic it is throwing java.util.NoSuchElementException.

CodePudding user response:

Don't shove a lambda on one gigantic line; it is now extremely hard to figure out where the exception is trying to point your attention to. Add some newlines to that thing! You're not iterating the list, you're calling forEach.

The .get() call at the very end is the likely culprit: Your stream operation ended up with 0 things; asking the 'maximum' out of 0 things results in no value. One of the One instances has a zero-length familyAge.

CodePudding user response:

max is returning an Optional. Calling get on an optional is usually a bad idea. Optional is used to wrap values that could potentially be null and if get would return null it throws a NoSuchElementException instead. A better solution could look something like this

myList1.stream()
    .forEach(list1 -> list1.getFamilyAge().stream()                    
        .max(Comparator.comparing(FamilyAge::getAId))
            .ifPresent(familyAge -> /* do something with family age*/));

As the name suggests ifPresent is only executed if the object is present.

  • Related