ストリームの最大インデックス値を取得する方法

ジョセフ・ホワン:

私は、以下のような自動生成されたID値を含むエンティティクラスを使用しています

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

しかし、このラインは、単純な集計値ではなく、ユーザークラス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);

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=211179&siteId=1