java reverse method 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: string reverse in java
String str = "Hello";
String reverse(String str){
StringBuilder sb = new StringBuilder();
sb.append(str);
sb.reverse();
return sb.toString();
}
Example 4: reverse a string in java
As we know that String is immutable. String class do not have reverse() method.