How to get the maximum index value of the stream

Joseph Hwang :

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?

Naman :

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);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=101317&siteId=1
Recommended