java-如何获取流的最大索引值

我正在使用包含自动生成的id值的Entity类,如下所示,

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

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

    @Column
    private String username;

我尝试使用JpaRepository接口在User类中获取id的最大值.
这是示例代码.

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

但是此行仅返回简单的计数值,而不返回User类ID值的最大值.如何使用流功能在User实体类获取最大id值?

最佳答案
您可以使用Stream.max找到它,例如:

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

或简单地作为

long maxId = UserJpaRepository.findAll().stream()
    .mapToLong(User::getId) // map to id
    .max() // find max
    .orElse(Long.MIN_VALUE);

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...