“This is the 9th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”
Java cycle
There are three main types of loop constructs in Java:
while
cycledo... while
cyclefor
cycle
while
cycle
While (Boolean expression) {// loop content}Copy the code
do... while
cycle
Do {// loop contents} while(Boolean expression);Copy the code
for
cycle
As with C++ 11, Java has two for loops, one similar to C:
For (initialize; Boolean expression; Update) {// code statement}Copy the code
There is another way to iterate over arrays:
for(type element: array)
{
System.out.println(element);
}
Copy the code
Declaration statement: Declares a new local variable whose type must match that of the array element. Its scope is limited to the loop block, and its value is equal to the value of the array element at that time. Expression: An expression is the name of the array to access, or a method that returns an array.
Such as:
public class Test {
public static void main(String args[]){
int [] numbers = {10.20.30.40.50};
for(int x : numbers ){
System.out.print( x );
System.out.print(",");
}
System.out.print("\n");
String [] names = {"James"."Larry"."Tom"."Lacy"};
for( String name : names ) {
System.out.print( name );
System.out.print(","); }}}Copy the code
Cycle control
Break and continue are also valid in Java.
Stream
In newer Java 8, Java provides a Stream class. You can process a collection of data (such as arrays, lists) more responsively, faster than a handwritten for loop and making your code easier. Such as:
int sum = widgets.stream()
.filter(w -> w.getColor() == RED)
.mapToInt(w -> w.getWeight())
.sum();
Copy the code
What this code does is filter out all the red ones in a list widges, then take their weights and sum them up. With Stream, the code is more focused on describing the problem, eliminating the tedious details of loop structure control statements. Also, Java automatically optimizes the stream handling process, probably faster than writing for manually.
If you do iOS development, Stream is syntactically similar to Swift Combine. After converting the collection data to a Stream object, we can use methods like map, filter, sorted, limit, forEach, etc.
For more information about Stream, see the official documentation: Java Docs: Stram
In my personal practice, this thing is relatively easy to use, used to do some sorting filtering, simple code, efficiency is really ok, if your production environment allows, these new Java 8 things are recommended to learn.