I have an object Patch that contains an Id, so let's say it has:
public class Patch {
private Long id;
public Patch(Long id) {
this.id = id;
}
public Long getId() {
return id;
}
}
Let's say I have a Collection of those patches of size > 0. So the Collection can contain 1 Patch object, or 10 Patch objects. I want to get the id value that is the largest of the Patches.
In other words, if I had 3 Patch objects with Ids:
patch1.getId() = 1;
patch3.getId() = 3;
patch2.getId() = 2;
Then the number I'd like to return would be 3. At this point in time, there is no order to the Collection. However, each new Patch will always have an Id that is 1 greater than the previous, starting at 1. In other words, if I added another patch with the above, the id would be guaranteed to be 4. If I had 10 Patch objects, the largest Id would be guaranteed to be 10.
I believe something like this would work, but might cause an issue when only 1 Patch exists:
Collections.max(patches, (p1, p2) -> Long.compare(p1.getId(), p2.getId())).getId();
or
patches.stream().max((p1, p2) -> Long.compare(p1.getId(), p2.getId())).get().getId();
but both of those seem... excessive... Is there a better way of doing this?
Also, the purpose of this is to avoid casting to long. Technically, the following works, but is frowned upon:
(long) patches.size()
Sure seems like it would be awfully convenient though...
Collections.max(patches, Comparator.comparing(Patch::getId)).getId();.comparingLong(), even