Collections: Collections.swap and rotate reorder a list without a new list

swap exchanges two indices in place, and rotate cyclically shifts every element by a distance, both operating directly on the given list.

Code
List<String> line = new ArrayList<>(List.of("A", "B", "C", "D", "E"));
Collections.swap(line, 0, 4);
System.out.println("After swap(0,4): " + line);
Collections.rotate(line, 2);
System.out.println("After rotate(2): " + line);
Output
After swap(0,4): [E, B, C, D, A]
After rotate(2): [D, A, E, B, C]
Advertisement
More in JAVA

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-09-27

© Java Coding Hub · About · Contact · Privacy · Terms