Loop through list reversely - Java Collection Framework

Java examples for Collection Framework:List

Description

Loop through list reversely

Demo Code

import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;

public class Main {
  public static void main(String[] args) {
    // add colors elements to list1
    String[] colors = { "black", "yellow", "green", "blue", "violet", "silver" };
    List<String> list1 = new LinkedList<>();

    for (String color : colors) {
      list1.add(color);//from  w w  w .ja  va  2 s .c  o m
    }
    printList(list1); // print list1 elements
    printReversedList(list1); // print list in reverse order
  }

  // output List contents
  private static void printList(List<String> list) {
    System.out.printf("%nlist:%n");

    for (String color : list)
      System.out.printf("%s ", color);

    System.out.println();
  }

  // print reversed list
  private static void printReversedList(List<String> list) {
    ListIterator<String> iterator = list.listIterator(list.size());

    System.out.printf("%nReversed List:%n");

    // print list in reverse order
    while (iterator.hasPrevious())
      System.out.printf("%s ", iterator.previous());
  }
}

Result


Related Tutorials