Why is this an issue?

Java 21 introduces the new Sequenced Collections API, which applies to all collections with a defined sequence on their elements, such as LinkedList, TreeSet, and others (see JEP 431). For projects using Java 21 and onwards, use this API instead of workaround implementations that were necessary before Java 21. One of the features of the new Sequenced Collections API is SequencedCollection.reversed() which returns a lightweight view of the original collection, in the reverse order.

This rule reports when reverse view would have been sufficient instead of a reverse copy of a sequenced collection created using a list constructor plus a Collections.reverse(collection); call.

If feasible, a view should be preferred over a copy because a view is a lightweight iterator without modification of the list itself.

How to fix it

Remove Collections.reverse(list); and replace list with list.reversed() after.

Code examples

Noncompliant code example

void foo() {
  var list = new ArrayList<String>();
  list.add("A");
  list.add("B");
  Collections.reverse(list); // Noncompliant
  for (var e : list) {
    // ...
  }
}

Compliant solution

void foo() {
  var list = new ArrayList<String>();
  list.add("A");
  list.add("B");
  for (var e : list.reversed()) {  // Compliant
    // ...
  }
}

Noncompliant code example

void foo(List<String> list) {
  var copy = new ArrayList<String>(list);
  Collections.reverse(copy); // Noncompliant
  for (var e : copy) {
    // ...
  }
}

Compliant solution

void foo(List<String> list) {
  for (var e : list.reversed()) {  // Compliant
    // ...
  }
}

Resources

Documentation