1

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...

2
  • Assuming non-null values, just use Collections.max(patches, Comparator.comparing(Patch::getId)).getId();. Commented Apr 6, 2016 at 16:24
  • @Pillar comparingLong(), even Commented Apr 6, 2016 at 16:24

1 Answer 1

3

You want the id, not the Patch, so you should find the max id, not the max Patch by id.

long a = patches.stream().mapToLong(Patch::getId).max().orElse(-1);
Sign up to request clarification or add additional context in comments.

5 Comments

.max().getAsLong() :p .max() returns an OptionalLong
@fge .getAsLong() :p
I went for orElse. When I use get() or getAsLong() people downvote.
awesome, thanks! Something to note is that, if going the get() route, I think you have to use getAsLong()?
Yes you do, sorry. When I said get I meant Optional.get().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.