Home > Mobile >  trying to get max from List is throwing Target Invocation Exception
trying to get max from List is throwing Target Invocation Exception

Time:12-10

I was trying to return the list by setting the object which has maximum value.

List<One> myList1 = getDetails();

I want to check "family" list and keep the element which has maximum of "fId" out of exisitng elements.

Below is the sample code tried, it is throwing TargetInvocationException

myList1.forEach(myList1 -> myList1.getFamily().stream()
        .max(Comparator.comparingLong(Family::getFId))
        .stream().findFirst()
        .orElse(null));

Sample class:

@Data
class One{
    private Long mId;
    private String mPolicyName;
    private List<Family> family;

}

@Data
class Family{
    private Long fId;
    private String fname;
    private String fStatus;
}

CodePudding user response:

You have a few things wrong. First, the forEach() doesn't do anything. Second, the Comparator is comparing fId which is an attribute of Family, not One. Finally, max() returns an Optional and you don't need to .stream().findFirst().

Assuming that class One has a setter method setFamily(List<Family> family), you can do:

myList1.forEach(one -> one.setFamily(one.getFamily().stream()
                .max(Comparator.comparingLong(Family::getFId))
                .stream().toList()));
  • Related