w3resource

Java generic method: Reverse list elements

Java Generic: Exercise-4 with Solution

Write a Java program to create a generic method that takes a list of any type and returns it as a new list with the elements in reverse order.

Sample Solution:

Java Code:

// ReverserList.java
// ReverserList Class
import java.util.ArrayList;
import java.util.List;

public class ReverserList {

  public static < T > List < T > reverseList(List < T > originalList) {
    List < T > reversedList = new ArrayList < > ();

    for (int i = originalList.size() - 1; i >= 0; i--) {
      reversedList.add(originalList.get(i));
    }

    return reversedList;
  }

  public static void main(String[] args) {
    List < Integer > numbers = List.of(1, 2, 3, 4, 5, 6);
    List < String > colors = List.of("Red", "Green", "Orange");

    List < Integer > reversedNumbers = reverseList(numbers);
    System.out.println("Original list of numbers: " + numbers);
    System.out.println("Reversed numbers: " + reversedNumbers); // Output: [6, 5, 4, 3, 2, 1]

    List < String > reversedWords = reverseList(colors);
    System.out.println("\nOriginal list of colors: " + colors);
    System.out.println("Reversed colors: " + reversedWords); // Output: [Orange, Green, Red]
  }
}

Sample Output:

 Original list of numbers: [1, 2, 3, 4, 5, 6]
Reversed numbers: [6, 5, 4, 3, 2, 1]

Original list of colors: [Red, Green, Orange]
Reversed colors: [Orange, Green, Red]

Explanation:

In this program, we define a generic method reverseList() that takes a list originalList as input. The method creates the reversedList from an ArrayList. It iterates over the originalList in reverse order using a for loop and adds each element to the reversedList with the add() method.

The method returns the reversedList at the end.

In the main() method, we demonstrate the reverseList() method by passing a list of integers (numbers) and a list of strings (words). We reverse the elements of each list and print the reversed list.

Flowchart:

Flowchart: Java generic method: Reverse list elements.

Java Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Find index of target element in list.
Next: Merge two lists alternately .

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/java-exercises/generic/java-generic-exercise-4.php