web123456

Stream:findFirst efficiently and succinctly traverses an element in a collection

Business development will be used to a lot of List<T> collection of data types, to store the business data we need, for example, there is a product yield information table T, the business needs to use thehistogramShow the production of each product each month illustration, that we defined an entity class ProductVO to pass these data, including the month month, the total number of count, product pro, through the production of information on the table in the SQL programmable, the number of production according to the month and the product grouping and summing, and ultimately return to the final in a List & lt; ProductVo & gt; in the.Call in the service layer to get the list collection, generally we are traversing through the for loop or iterator, do judgment, now java8 new features Stream can help us to complete the cycle of concise and efficient coding. Do not need to write a heavy heavy loop

The code is as follows:

  1. // Call the dao layer method to get the collection data that will group the outputs.
  2. List<ProductVO > list= ();
  3. // take out the element whose month is equal to 5 through stream, findFirst takes the first element
  4. ProductVO vo = ().filter(f->(())=5).findFirst().get();

 Stream(used form a nominal expression)findFirstmethod looks for the first element in this stream as theOptionalThe get method returns the processed element. The get method returns the processed element.

in the event thatfindFirstThe selected elements arenullIt will throw theNullPointerException

Problems that may be encountered:

NoSuchElementException: you can use this method to filter the orElse method if you have a null pointer:

Replace .get() with .orElse(null), which will return the null value. No more errors will be reported