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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With