• Skip to main content
  • Skip to after header navigation
  • Skip to site footer

Free-Mail

  • Events
  • Images
    • Instagram Goodness
  • Music
  • News
  • Software

A guide to Java for loops

A guide to Java for loops: A guide to Java for loops sethkenlon Fri, 01/20/2023 – 03:00

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

More on Java
What is enterprise Java programming?
An open source alternative to Oracle JDK
Java cheat sheet
Red Hat build of OpenJDK
Free online course: Developing cloud-native applications with microservices
Fresh Java articles

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 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.

This article covers how to use the Java for loop and the Java Stream method.

Coffee beans
Image by:

Pixabay. CC0.

Java

What to read next
Creative Commons LicenseThis work is licensed under a Creative Commons Attribution-Share Alike 4.0 International License.
Register or Login to post a comment.

: Opensource.com sethkenlon

Supporting Open Source.

Have you tried: Diving with Sharks?

Share this:

  • Share on Facebook (Opens in new window) Facebook
  • Share on X (Opens in new window) X
  • Share on Pinterest (Opens in new window) Pinterest
  • Email a link to a friend (Opens in new window) Email
  • More
  • Share on Tumblr (Opens in new window) Tumblr
  • Print (Opens in new window) Print
  • Share on LinkedIn (Opens in new window) LinkedIn
  • Share on Reddit (Opens in new window) Reddit
Published on 20 January 2023 by Alan Category: SoftwareTag: Guide, java, Loops

September in Review: 11 Top Health Press Releases

A roundup of the most newsworthy healthcare press releases from PR Newswire, including new funding …

Read moreSeptember in Review: 11 Top Health Press Releases

Famous Birthdays for 12th February 2026

1865 – Kazimierz Tetmajer, Polish writer and poet (Young Poland), born in Lud?mierz, Galicia …

Read moreFamous Birthdays for 12th February 2026

Glass Onion shows the pitfalls of going into business with friends – here’s how you can succeed

Glass Onion shows the pitfalls of going into business with friends – here’s how you can …

Read moreGlass Onion shows the pitfalls of going into business with friends – here’s how you can succeed

About Alan

Previous Post:Trending Now: David Crosby
Next Post:accolade

Reach Trust

Reach Trust is a holding trust for a number of companies within the Stratlec Group.

Copyright © 2026 · Free-Mail · All Rights Reserved · Powered by Straton Electrical

Back to top