reverse method array java code example
Example 1: reverse array in java
int length = array.length;
for(int i=0;i<length/2;i++) {
int swap = array[i];
array[i] = array[length-i-1];
array[length-i-1] = swap;
}
or
Collections.reverse(Arrays.asList(array));
Example 2: how to reverse a list in java
List<String> stringList = Arrays.asList("A", "B", "C");
Collections.reverse(stringList);
assertThat(stringList).containsExactly("C", "B", "A");
Example 3: Java reverse string array
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class ReverseStringArrayUsingCollections
{
public static void main(String[] args)
{
List<String> li = new ArrayList<String>();
li.add("java");
li.add("core");
li.add("world");
li.add("hello");
System.out.println("Given list: " + li);
Collections.reverse(li);
System.out.println("After using collections: " + li);
}
}
Example 4: reverse array java
for(int i=intArray.length-1;i>=0;i--)
System.out.print(intArray[i] + " ");