ArrayLists are dynamic arrays that are part of the Java collections framework…

Prerequisites

Before diving into the various ways to print ArrayLists, you should have…

Printing ArrayLists Using For Loop

The easiest way to print all elements of an ArrayList is to iterate through them using an enhanced for loop:

import java.util.ArrayList;

public class Main {

  public static void main(String[] args) {

    ArrayList<String> fruits = new ArrayList<>();

    fruits.add("Apple");
    fruits.add("Mango");
    fruits.add("Banana");

    for (String fruit : fruits) {
      System.out.println(fruit);
    }

  }

}

We can also access the elements by index using a standard for loop:

for(int i = 0; i < fruits.size(); i++) {
  System.out.println(fruits.get(i)); 
}

Finally, we can print the ArrayList object directly:

System.out.println(fruits);

For loops provide simple iteration to access and print elements.

Printing ArrayLists Using While Loop

A while loop can also iterate through an ArrayList:

int i = 0;
while (i < fruits.size()) {
  System.out.println(fruits.get(i));
  i++; 
}

While loops print the ArrayList similar to for loops, but with manual index tracking.

Printing ArrayLists Using Iterator

Another way to traverse ArrayLists is using an iterator:

Iterator iterator = fruits.iterator(); 
while (iterator.hasNext()) {
  String fruit = (String) iterator.next();   
  System.out.println(fruit);
}  

The iterator starts before the first element. hasNext() checks for more elements, and next() retrieves each element for printing.

Using iterator explicitly can be beneficial compared to for and while loops in some cases – like removing elements during iteration.

Printing ArrayLists Using ForEach (Java 8+)

Java 8 introduced a new built-in forEach approach:

fruits.forEach(fruit -> {
  System.out.println(fruit);   
});

Here we pass a lambda to print each element. ForEach loops abstract away manual control flow.

Printing ArrayLists Using Streams

Java 8 streams also provide iteration via the forEach operator:

fruits.stream()
      .forEach(System.out::println);

The stream applies println to each element through a method reference.

Print ArrayLists of Custom Classes

For loops also work for printing custom classes:

class Person {
  String name;
  int age;

  //Constructor, getters setters   
}

ArrayList<Person> people = new ArrayList<>; 

people.add(new Person("John", 30));

for(Person p : people) {
  System.out.print(p.getName());
  System.out.println(" - " + p.getAge());  
}

This iterates the people ArrayList, accessing name and age properties of each Person.

Print Sublists from ArrayLists

We can also print subsections of an ArrayList using subList():

ArrayList<Integer> list = new ArrayList<>();

// add elements  

ArrayList<Integer> sub = list.subList(2, 6); 

for(Integer n : sub) {
  System.out.println(n);   
}

subList() returns elements between the specified start (inclusive) and end (exclusive) indexes. Printing sublists can be useful for partitioning data.

Format ArrayList Output

We can customize ArrayList output formatting using concatenation and printf():

for(String fruit : fruits) {

  String formatted = fruit + " are tasty";  

  System.out.printf("%-15s %4d calories\n", formatted, fruitCals.get(fruit)); 

} 

This concatenates strings, then uses formatted print with alignment and width modifiers to output a table-style format.

ArrayList Performance

While simple to use, ArrayLists have nuanced performance vs traditional arrays. Prints inside vs outside loops, initial capacity, and GrowthPolicy all impact efficiency.

As a full-stack developer, properly benchmarking these factors is key for optimal system design. Architecting performant, scalable solutions requires deep expertise.

Summary

In this comprehensive 2600+ word guide, you learned a multitude of effective ways to print ArrayList elements in Java…

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *