Get to the abbreviations from 5 examples of iterating Java lists

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.

Imperative style

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.

1. for loop (index specification)

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));
}

2. for loop (no index specified)

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);
}

Functional style

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.

  1. foreach() Consumer foreach () takes a Consumer type as an argument, but this instance processes the argument received by the accept () method. Each element in the list is passed to the accept () method one by one, so it is output as standard in that.

foreach-comsumer


months.forEach(new Consumer<String>() {
  public void accept(final String month) {
    System.out.println(month);
  }
});
  1. foreach() Lambda You can use a Lambda expression to replace an anonymous inner class (below a Consumer instance).

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));

5. See foreach () method

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

Get to the abbreviations from 5 examples of iterating Java lists
[Java] How to get the authority of the folder
[Java] How to get the URL of the transition source
How to write Scala from the perspective of Java
[Java] How to get the maximum value of HashMap
How to get the longest information from Twitter as of 12/12/2016
The road from JavaScript to Java
From fledgling Java (3 years) to Node.js (4 years). And the impression of returning to Java
[Java] How to convert from String to Path type and get the path
How to get the length of an audio file in java
Get the result of POST in Java
[Java] Get the day of the specific day of the week
[Java] How to get the current directory
How to get the date in java
Output of the book "Introduction to Java"
[Java] How to get to the front of a specific string using the String class
How to get the absolute path of a directory running in Java
From Java9, the constructor of the class corresponding to primitive types is deprecated.
I want to get the field name of the [Java] field. (Old tale tone)
I translated the grammar of R and Java [Updated from time to time]
[Java] Get MimeType from the contents of the file with Apathce Tika [Kotlin]
[Java] From two Lists to one array list
[Java] Get the length of the surrogate pair string
How to get Class from Element in Java
How to get today's day of the week
[Java] How to get the redirected final URL
Java Welcome to the Swamp of 2D Arrays
[Promotion of Ruby comprehension (1)] When switching from Java to Ruby, first understand the difference.
[Java] Program example to get the maximum and minimum values from an array
[Java] How to easily get the longest character string of ArrayList using stream
Sample code to get the values of major SQL types in Java + MySQL 8.0
Changes from Java 8 to Java 11
Sum from Java_1 to 100
From Java to Ruby !!
Get the URL of the HTTP redirect destination in Java
From the introduction of devise to the creation of the users table
[Java] I want to calculate the difference from the date
[Java] How to extract the file name from the path
The story of migrating from Paperclip to Active Storage
Java language from the perspective of Kotlin and C #
Source used to get the redirect source URL in Java
[Java] Get the file in the jar regardless of the environment
As of April 2018 How to get Java 8 on Mac
[Android] How to get the setting language of the terminal
[Rails] How to get the contents of strong parameters
Java: Use Stream to sort the contents of the collection
[Swift] How to get the document ID of Firebase
[Swift] Use Swity JSON to easily get information from JSON data of the fortune-telling API
How to get the class name of the argument of LoggerFactory.getLogger when using SLF4J in Java
When inserting from Java to MySQL, get Auto_Increment_ID (automatic numbering value) as the return value
The story of raising Spring Boot from 1.5 series to 2.1 series part2
Java to fly data from Android to ROS of Jetson Nano
Migration from Cobol to JAVA
[JDBC] I tried to access the SQLite3 database from Java.
I tried to summarize the basics of kotlin and java
New features from Java7 to Java8
[IOS] How to get the table name from AWS DynamoDB
20190803_Java & k8s on Azure The story of going to the festival
Command to check the number and status of Java threads
Connect from Java to PostgreSQL
Sample code to get the values of major SQL types in Java + Oracle Database 12c