A guide to Java for loops

This article covers how to use the Java for loop and the Java Stream method.
No readers like this yet.
Coffee beans

Pixabay. CC0.

In programming, you often need your code to iterate over a set of data to process each item individually. You use control structures to direct the flow of a program, and the way you tell your code what to do is by defining a condition that it can test. For instance, you might write code to resize an image until all images have been resized once. But how do you know how many images there are? One user might have five images, and another might have 100. How do you write code that can adapt to unique use cases? In many languages, Java included, one option is the for loop. Another option for Java is the Stream method. This article covers both.

For loop

A for loop takes a known quantity of items and ensures that each item is processed. An "item" can be a number, or it can be a table containing several entries, or any Java data type. This essentially describes a counter:

  • Starting value of the counter

  • Stop value

  • The increment you want the counter to advance

For instance, suppose you have three items, and you want Java to process each one. Start your counter (call it c) at 0 because Java starts the index of arrays at 0. Set the stop value to c < 3 or c ⇐ 2. Finally, increment the counter by 1. Here's some sample code:

package com.opensource.example;

public class Main {
  public static void main(String[] args) {

      String[] myArray = {"zombie", "apocalypse", "alert" };

    for (int i = 0; i < 3; i++) {
        System.out.printf("%s ", myArray[i]);
    }
  }
}

Run the code to ensure all three items are getting processed:

$ java ./for.java
zombie apocalypse alert

The conditions are flexible. You can decrement instead of increment, and you can increment (or decrement) by any amount.

The for loop is a common construct in most languages. However, most programming languages are actively developed, and certainly, Java is always improving. There's a new way to iterate over data, and it's called Java Stream.

Java Stream

The Java Stream interface is a feature of Java providing functional access to a collection of structured data. Instead of creating a counter to "walk" through your data, you use a Stream method to query the data:

package com.opensource.example;

import java.util.Arrays;
import java.util.stream.Stream;

public class Example {
  public static void main(String[] args) {
    // create an array
    String[] myArray = new String[]{"plant", "apocalypse", "alert"};

    // put array into Stream
    Stream<String> myStream = Arrays.stream(myArray);

    myStream.forEach(e -> System.out.println(e));
    }
  }

In this sample code, you import the java.util.stream.Stream library for access to the Stream construct, and java.util.Arrays to move an array into the Stream.

In the code, you create an Array as usual. Then you create a stream called myStream and put the data from your array into it. Those two steps are broadly typical of Stream usage: You have data, so you put the data into a Stream so you can analyze it.

What you do with the Stream depends on what you want to achieve. Stream methods are well documented in Java docs, but to mimic the basic example of the for loop it makes sense to use the forEach or forEachOrdered method, which iterates over each element in the Stream. In this example, you use a lambda expression to create a parameter, which is passed to a print statement:

$ java ./stream.java
plant
apocalypse
alert

When to use Stream

Streams don't really exist to replace for loops. In fact, Streams are intended as ephemeral constructs that don't need to be stored in memory. They're intended to gather data for analysis and then disappear.

For instance, watch what happens if you try to use a Stream twice:

package com.opensource.example;

import java.util.Arrays;
import java.util.stream.Stream;

public class Example {
  public static void main(String[] args) {
    // create an array
    String[] myArray = new String[]{"plant", "apocalypse", "alert"};

    // put array into Stream
    Stream<String> myStream = Arrays.stream(myArray);

    long myCount = myStream.count();
    System.out.println(myCount);
    }
  }

This won't work, and that's intentional:

$ java ./stream.java
Exception in thread "main"
stream has already been operated upon or closed

Part of the design philosophy of Java Stream is that you bring data into your code. You then apply filters up front rather than writing a bunch of if-then-else statements in a desperate attempt to find the data you actually want, process the data, and then dispose of the Stream. It's similar to a Linux pipe, in which you send the output of an application to your terminal only to filter it through grep so you can ignore all the data you don't need.

Here's a simple example of a filter to eliminate any entry in a data set that doesn't start with an a:

package com.opensource.example;

import java.util.Arrays;
import java.util.stream.Stream;

public class Example {
  public static void main(String[] args) {
    String[] myArray = new String[]{"plant", "apocalypse", "alert"};
    Stream<String> myStream = Arrays.stream(myArray).filter(s -> s.startsWith("a"));
    myStream.forEach(e -> System.out.println(e));
    }
  }

Here's the output:

$ java ./stream.java
apocalypse
alert

For data you intend to use as a resource throughout your code, use a for loop.

For data you want to ingest, parse, and forget, use a Stream.

Iteration

Iteration is common in programming, and whether you use a for loop or a Stream, understanding the structure and the options you have means you can make intelligent decisions about how to process data in Java.

For advanced usage of Streams, read Chris Hermansen's article Don't like loops? Try Java Streams.

Tags
Seth Kenlon
Seth Kenlon is a UNIX geek, free culture advocate, independent multimedia artist, and D&D nerd. He has worked in the film and computing industry, often at the same time.

Comments are closed.

Creative Commons LicenseThis work is licensed under a Creative Commons Attribution-Share Alike 4.0 International License.