4/27: Please point out and correct the description. (for statement-> forEach statement, forEach statement-> forEach method)
To get used to the forEach method, let's rewrite the processing of the forEach statement.
Before First, the source of the for Each statement.
OtamesiFizzBuzz.java
package oasobi;
import java.util.ArrayList;
/**
 *practice.
 *
 */
public class OtamesiFizzBuzz {
	public static void main(String[] args) {
		OtamesiFizzBuzz2 main = new OtamesiFizzBuzz2();
		main.execute();
	}
	//Run
	public void execute() {
		//Preparation
		ArrayList<Integer> list = new ArrayList<>();
		for(int i = 1 ; i < 16 ; i++) {
            list.add(i);
        }
		//Try turning
		for(int i : list) {
			outputFizzBuzz(i);
        }
	}
	//Outputs Fizz if the argument is divisible by 3, Buzz if it is divisible by 5, and FizzBuzz if it is divisible by both.
	//If neither is divisible"It's neither!"
	private void outputFizzBuzz(int value) {
		if (value%3 == 0 && value%5 == 0) {
			System.out.println(value + ":FizzBuzz");
		} else if (value%3 == 0 && value%5 != 0) {
			System.out.println(value + ":Fizz");
		} else if (value%3 != 0 && value%5 == 0) {
			System.out.println(value + ":Buzz");
		} else {
			System.out.println(value + ":It's neither!");
		}
	}
}
■ Execution result 1: Neither! 2: Neither! 3:Fizz 4: Neither! 5:Buzz 6:Fizz 7: Neither! 8: Neither! 9:Fizz 10:Buzz 11: Neither! 12:Fizz 13: Neither! 14: Neither! 15:FizzBuzz
After Let's rewrite this with the forEach method.
OtamesiFizzBuzz2.java
package oasobi;
import java.util.ArrayList;
/**
 *Practice # 2.
 *
 */
public class OtamesiFizzBuzz2 {
	public static void main(String[] args) {
		OtamesiFizzBuzz2 main = new OtamesiFizzBuzz2();
		main.execute();
	}
	//Run
	public void execute() {
		//Preparation
		ArrayList<Integer> list = new ArrayList<>();
		for(int i = 1 ; i < 16 ; i++) {
            list.add(i);
        }
		//Try turning
		list.forEach(this::outputFizzBuzz);
	}
	//Outputs Fizz if the argument is divisible by 3, Buzz if it is divisible by 5, and FizzBuzz if it is divisible by both.
	//If neither is divisible"It's neither!"
	private void outputFizzBuzz(int value) {
		if (value%3 == 0 && value%5 == 0) {
			System.out.println(value + ":FizzBuzz");
		} else if (value%3 == 0 && value%5 != 0) {
			System.out.println(value + ":Fizz");
		} else if (value%3 != 0 && value%5 == 0) {
			System.out.println(value + ":Buzz");
		} else {
			System.out.println(value + ":It's neither!");
		}
	}
}
■ Execution result 1: Neither! 2: Neither! 3:Fizz 4: Neither! 5:Buzz 6:Fizz 7: Neither! 8: Neither! 9:Fizz 10:Buzz 11: Neither! 12:Fizz 13: Neither! 14: Neither! 15:FizzBuzz
I got the same result.
I feel like I somehow understood that I passed a method that takes one argument to the forEach method. A little refreshing.
Recommended Posts