- Java Programming Examples
- Example - Home
- Example - Environment
- Example - Strings
- Example - Arrays
- Example - Date & Time
- Example - Methods
- Example - Files
- Example - Directories
- Example - Exceptions
- Example - Data Structure
- Example - Collections
- Example - Networking
- Example - Threading
- Example - Applets
- Example - Simple GUI
- Example - JDBC
- Example - Regular Exp
- Example - Apache PDF Box
- Example - Apache POI PPT
- Example - Apache POI Excel
- Example - Apache POI Word
- Example - OpenCV
- Example - Apache Tika
- Example - iText
- Java Tutorial
- Java - Tutorial
- Java Useful Resources
- Java - Quick Guide
- Java - Useful Resources
How to reverse a collection in Java
Problem Description
How to reverse a collection?
Solution
Following example demonstratres how to reverse a collection with the help of listIterator() and Collection.reverse() methods of Collection and Listiterator class.
import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.ListIterator; public class UtilDemo3 { public static void main(String[] args) { String[] coins = { "A", "B", "C", "D", "E" }; List l = new ArrayList(); for (int i = 0; i < coins.length; i++)l.add(coins[i]); ListIterator liter = l.listIterator(); System.out.println("Before reversal"); while (liter.hasNext())System.out.println(liter.next()); Collections.reverse(l); liter = l.listIterator(); System.out.println("After reversal"); while (liter.hasNext())System.out.println(liter.next()); } }
Result
The above code sample will produce the following result.
Before reversal A B C D E After reversal E D C B A
java_collections.htm
Advertisements
To Continue Learning Please Login
Login with Google