LoginSignup
9

More than 5 years have passed since last update.

【Java】Streamで要素存在チェック

Posted at

Stream#isEmptyというメソッドは無いので、どう書くのがベストなのかわからなくてQiitaに書きます。

まず普通のときは下記のように書くと思います。

list.stream()
        .anyMatch(条件ラムダ式orメソッド参照);

が、今回は、単純にList#isEmptyのような判定をStreamに対して行いたい場合はどう書くのがいいのだろう?というネタです。

例えば、Doma2でquery投げて返ってきたStreamに結果があるのか無いのかだけ判定したい、とかで使うかもしれません。

結果、どれがベストかという答えはわからないですが考えたパターンをつらつら書きます。

anyMatchで常にtrue

初見ではちょっとギョッとするかも。

    boolean notEmpty = stream()
            .anyMatch(e -> true);

    System.out.println(notEmpty);

Iterator#hasNext

説明変数が無いとパッと見何がしたいのかわからない印象。

    boolean notEmpty = stream()
            .iterator()
            .hasNext();

    System.out.println(notEmpty);

Optional#isPresent

うーん。

    boolean notEmpty = stream()
            .findAny()
            .isPresent();

    System.out.println(notEmpty);

count

無駄が多いのでNG。

    boolean notEmpty = stream()
            .count() > 0;

    System.out.println(notEmpty);

1 or 0 になるようにcount

まだこのほうがマシ。

    //まだまし
    boolean notEmpty = stream()
            .limit(1)
            .count() > 0;

    System.out.println(notEmpty);

toList

これも無駄が多いのでNG。

    boolean notEmpty = !stream()
            .collect(Collectors.toList())
            .isEmpty();

    System.out.println(notEmpty);

効率的はIterator#hasNextのパターンが良いんですかね?(特にDoma2で使うなら)
その場面にあったら何も考えずに一番簡単そうなanyMatch(e -> true)で書いてしまうかな。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9