* BAEL-1328 How to Invert an Array in Java

* Removing code from evaluation article.

* BAEL-1328
Adjusting spaces and implement inversion with commons lang3 and guava.

* BAEL-1328 Renaming unit test class; using AssertJ.
This commit is contained in:
André Thiago 2017-12-05 23:43:23 -03:00 committed by KevinGilmore
parent 550978ab76
commit 5477f80a1c
2 changed files with 90 additions and 0 deletions

View File

@ -0,0 +1,41 @@
package com.baeldung.array;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.IntStream;
import org.apache.commons.lang3.ArrayUtils;
import com.google.common.collect.Lists;
public class ArrayInverter {
public void invertUsingFor(Object[] array) {
for (int i = 0; i < array.length / 2; i++) {
Object temp = array[i];
array[i] = array[array.length - 1 - i];
array[array.length - 1 - i] = temp;
}
}
public void invertUsingCollectionsReverse(Object[] array) {
List<Object> list = Arrays.asList(array);
Collections.reverse(list);
}
public Object[] invertUsingStreams(final Object[] array) {
return IntStream.range(1, array.length + 1).mapToObj(i -> array[array.length - i]).toArray();
}
public void invertUsingCommonsLang(Object[] array) {
ArrayUtils.reverse(array);
}
public Object[] invertUsingGuava(Object[] array) {
List<Object> list = Arrays.asList(array);
List<Object> reverted = Lists.reverse(list);
return reverted.toArray();
}
}

View File

@ -0,0 +1,49 @@
package com.baeldung.array;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
public class ArrayInverterUnitTest {
private String[] fruits = { "apples", "tomatoes", "bananas", "guavas", "pineapples", "oranges" };
@Test
public void invertArrayWithForLoop() {
ArrayInverter inverter = new ArrayInverter();
inverter.invertUsingFor(fruits);
assertThat(new String[] { "oranges", "pineapples", "guavas", "bananas", "tomatoes", "apples" }).isEqualTo(fruits);
}
@Test
public void invertArrayWithCollectionsReverse() {
ArrayInverter inverter = new ArrayInverter();
inverter.invertUsingCollectionsReverse(fruits);
assertThat(new String[] { "oranges", "pineapples", "guavas", "bananas", "tomatoes", "apples" }).isEqualTo(fruits);
}
@Test
public void invertArrayWithStreams() {
ArrayInverter inverter = new ArrayInverter();
assertThat(new String[] { "oranges", "pineapples", "guavas", "bananas", "tomatoes", "apples" }).isEqualTo(inverter.invertUsingStreams(fruits));
}
@Test
public void invertArrayWithCommonsLang() {
ArrayInverter inverter = new ArrayInverter();
inverter.invertUsingCommonsLang(fruits);
assertThat(new String[] { "oranges", "pineapples", "guavas", "bananas", "tomatoes", "apples" }).isEqualTo(fruits);
}
@Test
public void invertArrayWithGuava() {
ArrayInverter inverter = new ArrayInverter();
assertThat(new String[] { "oranges", "pineapples", "guavas", "bananas", "tomatoes", "apples" }).isEqualTo(inverter.invertUsingGuava(fruits));
}
}