SoFunction
Updated on 2025-03-08

Analysis of the operation example of the Stream short-circuit terminal in Java8 new feature

This article mainly introduces the analysis of the operation example of the new Java8 feature Stream short-circuit terminal. The example code is introduced in this article in detail, which has certain reference value for everyone's learning or work. Friends who need it can refer to it.

Pass in a predicate, return to the pass as boolean, and if the condition meets the condition, the stream will be directly ended.

  • Match all allMatches
  • Any match anymMatch
  • NoneMatch
  • Find the first findFirst
  • Find any findAny

Match all allMatches

/Match all allMatch
@Test
public void allMatchTest() {
  boolean b = ()
      //The prices of all products are greater than 40      .allMatch(sku -> () > 40);
  (b);
  /** Return value
    * true
    */
}

Any match anymMatch

//Arbitrary match anymMatch@Test
public void anyMatchTest() {
  boolean b = ()
      //As long as there is a totalNum number of 3, it will reverse true      .anyMatch(sku -> () == 3);
  (b);
  /** Output result:
    * true
    */
}

NoneMatch

//Doesn't match noneMatch@Test
public void noneMatchTest() {
  boolean b = ()
      //There is no totalNum of 2, so the return value is true.      .noneMatch(sku -> () == 2);
  (b);
  /**
    * Select true if there is no match
    */
}

Find the first findFirst

//Find the first findFirst@Test
public void findFirstTest() {
  //My own Optional has an introduction, findFirst() method, and it will return as long as there is the first one.  Optional<Sku> first = ().findFirst();
  //Take the value from Optional  Sku sku = ();
  //Output result than json format  ((sku,true));
  /**
    * {
    * "skuCategory":"ELECTRONICS",
    * "skuId":100001,
    * "skuName":"drone",
    * "skuPrice":4999.0,
    * "totalNum":1,
    * "totalPrice":4999.0
    * }
    */
}

Find any findAny

//Find any findAny@Test
public void findAnyTest() {
  //Take any one from the list  Optional<Sku> any = ().findAny();
  //Get the value from Optional  Sku sku = ();
  //Output result with json  ((sku, true));
  /**
    * {
    * "skuCategory":"ELECTRONICS",
    * "skuId":100001,
    * "skuName":"drone",
    * "skuPrice":4999.0,
    * "totalNum":1,
    * "totalPrice":4999.0
    * }
    */
}

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.