To reverse the order of LinkedList
elements we can use the reverse(List<?> list)
static method of java.util.Collections
class. Here is the example:
package org.kodejava.util;
import java.util.LinkedList;
import java.util.Collections;
public class LinkedListReverseOrder {
public static void main(String[] args) {
LinkedList<String> grades = new LinkedList<>();
grades.add("A");
grades.add("B");
grades.add("C");
grades.add("D");
grades.add("E");
grades.add("F");
System.out.println("Output in original order:");
System.out.println("=========================");
for (String grade : grades) {
System.out.println("Grade = " + grade);
}
// Reverse the element order in the linked list object.
Collections.reverse(grades);
System.out.println("Output in reverse order:");
System.out.println("=========================");
for (String grade : grades) {
System.out.println("Grade = " + grade);
}
}
}
Here is the output of the program:
Output in original order:
=========================
Grade = A
Grade = B
Grade = C
Grade = D
Grade = E
Grade = F
Output in reverse order:
=========================
Grade = F
Grade = E
Grade = D
Grade = C
Grade = B
Grade = A
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024