Let's look at how to write a list iterator using a simple list. This time we will use the following list of strings.
list
final List<String> months =
Arrays.asList("January", "February", "March", "April", "May", "June", "July", "Augast", "September", "October", "November", "December");
I just want these elements to be standard output in sequence.
First, let's use a for loop. The for loop is an imperative style, an external iterator. In the imperative style, the programmer has to think a lot about "how" to do it.
I don't think it's particularly difficult. Outputs in order from the first element. You need to specify the index by incrementing it one by one.
for-with-index
for (int i = 0; i < months.size(); i++) {
System.out.println(months.get(i));
}
If you don't need an index, Java provides more advanced control syntax than a simple for loop. Behind the scenes, the Iterator interface is applied and the hasNext () and next () methods are called. Therefore, it is not necessary for the programmer to specify the end of the loop using the size of the list.
for-without-index
for (final String month : months) {
System.out.println(month);
}
Java8 has added a forEach method to the Iterable interface. It's a functional style, an internal iterator. The functional style makes it easier to focus on thinking about what to do.
foreach-comsumer
months.forEach(new Consumer<String>() {
public void accept(final String month) {
System.out.println(month);
}
});
foreach-lambda
months.forEach((final String month) -> System.out.println(month));
Since the Java compiler can perform type inference, it can be omitted as follows. However, in this case, final is missed and it is no longer an immutable argument.
foreach-lambda
months.forEach(month -> System.out.println(month));
Method references are a feature from Java8, and the class name :: method name is the basic form. Since the method that has already been defined can be executed without specifying the argument, it will be further omitted.
foreach-method-reference
months.forEach(System.out::println);
Recommended Posts