Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the maximum index value of the stream

I am using Entity class containing auto generated id value like below,

@Entity
@Table(name="BlogUser")
public class User {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column
    private Long id;

    @Column
    private String username;

I try to get the maximum value of id in User class with JpaRepository Interface. This is the sample codes.

UserJpaRepository.findAll().stream().count();

But this line returns the only simple counting value, not the maximum value of User class id value. How can I get the maximum id value in User entity class with stream function?

like image 892
Joseph Hwang Avatar asked Sep 09 '25 11:09

Joseph Hwang


1 Answers

You can find it using Stream.max like :

Long maxId = UserJpaRepository.findAll().stream()
    .map(User::getId) // mapping to id
    .max(Comparator.naturalOrder()) // max based on natural comparison
    .orElse(Long.MIN_VALUE); // if nothing element is mapped

or simply as

long maxId = UserJpaRepository.findAll().stream()
    .mapToLong(User::getId) // map to id
    .max() // find max
    .orElse(Long.MIN_VALUE);
like image 97
Naman Avatar answered Sep 11 '25 02:09

Naman