javaspringjava-stream

Sort list comparing only the first string from list of objects inside the initial list


I have a list of myDto objects

public class myDto {
    
    private String requestId;
    private List<Dogs> dogs;
    
}

I can sort the list comparing requestIds by

myDtoList.sort(Comparator.comparing(f -> f.getRequestId));

If the Dog object looks like this

public class Dog {
    
    private String name;    
}

Is it possible and how can I sort the initial list comparing only the first items from each dog's list? So no matter how many dogs are in the list to compare only the first dog entries in each myDto object.

Let's say I have myDtoList with 3 entries 1, 2, 3.

Entry 1 has a dog named "Zoro" thats first in the list of dogs with many more.

Entry 2 has a dog named "Fancy" thats first in the list of dogs with many more.

Entry 3 has a dog named "Ann" thats first in the list of dogs with many more.

After sorting they will be entry 3, entry 2, entry 1


Solution

  • I assume you can get the first item's name via getDogs().get(0).getName(). If the list is allowed to be empty, you can do

    getDogs() != null && getDogs().size() > 0 ? getDogs().get(0).getName() : null;
    

    Use this instead of getRequestId().