This commit is contained in:
vatsalgosar
2019-10-12 16:05:56 +05:30
3028 changed files with 28226 additions and 14020 deletions

View File

@@ -1,25 +0,0 @@
*.class
0.*
#folders#
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
.resourceCache
# Packaged files #
*.jar
*.war
*.ear
# Files generated by integration tests
backup-pom.xml
/bin/
/temp
#IntelliJ specific
.idea/
*.iml

View File

@@ -1,5 +0,0 @@
## Relevant Articles
- [Extending an Arrays Length](https://www.baeldung.com/java-array-add-element-at-the-end)
- [Checking If an Array Is Sorted in Java](https://www.baeldung.com/java-check-sorted-array)
- [Looping Diagonally Through a 2d Java Array](https://www.baeldung.com/java-loop-diagonal-array)

View File

@@ -0,0 +1,15 @@
## Core Java Arrays (Part 2)
This module contains articles about Java arrays
## Relevant Articles
- [Extending an Arrays Length](https://www.baeldung.com/java-array-add-element-at-the-end)
- [Looping Diagonally Through a 2d Java Array](https://www.baeldung.com/java-loop-diagonal-array)
- [Converting Between Stream and Array in Java](https://www.baeldung.com/java-stream-to-array)
- [Convert a Float to a Byte Array in Java](https://www.baeldung.com/java-convert-float-to-byte-array)
- [Array Operations in Java](https://www.baeldung.com/java-common-array-operations)
- [Intersection Between two Integer Arrays](https://www.baeldung.com/java-array-intersection)
- [Removing an Element from an Array in Java](https://www.baeldung.com/java-array-remove-element)
- [Removing the First Element of an Array](https://www.baeldung.com/java-array-remove-first-element)
- [[<-- Prev]](/core-java-modules/core-java-arrays)

View File

@@ -0,0 +1,34 @@
package com.baeldung.array;
import java.util.ArrayList;
import java.util.Arrays;
public class AddElementToEndOfArray {
public Integer[] addElementUsingArraysCopyOf(Integer[] srcArray, int elementToAdd) {
Integer[] destArray = Arrays.copyOf(srcArray, srcArray.length + 1);
destArray[destArray.length - 1] = elementToAdd;
return destArray;
}
public Integer[] addElementUsingArrayList(Integer[] srcArray, int elementToAdd) {
Integer[] destArray = new Integer[srcArray.length + 1];
ArrayList<Integer> arrayList = new ArrayList<>(Arrays.asList(srcArray));
arrayList.add(elementToAdd);
return arrayList.toArray(destArray);
}
public Integer[] addElementUsingSystemArrayCopy(Integer[] srcArray, int elementToAdd) {
Integer[] destArray = new Integer[srcArray.length + 1];
System.arraycopy(srcArray, 0, destArray, 0, srcArray.length);
destArray[destArray.length - 1] = elementToAdd;
return destArray;
}
}

View File

@@ -0,0 +1,27 @@
package com.baeldung.array;
import org.apache.commons.lang3.ArrayUtils;
public class RemoveElementFromAnArray {
public int[] removeAnElementWithAGivenIndex(int[] array, int index) {
return ArrayUtils.remove(array, index);
}
public int[] removeAllElementsWithGivenIndices(int[] array, int... indicies) {
return ArrayUtils.removeAll(array, indicies);
}
public int[] removeFirstOccurrenceOfGivenElement(int[] array, int element) {
return ArrayUtils.removeElement(array, element);
}
public int[] removeAllGivenElements(int[] array, int... elements) {
return ArrayUtils.removeElements(array, elements);
}
public int[] removeAllOccurrencesOfAGivenElement(int[] array, int element) {
return ArrayUtils.removeAllOccurences(array, element);
}
}

View File

@@ -0,0 +1,44 @@
package com.baeldung.array.conversions;
import java.nio.ByteBuffer;
public class FloatToByteArray {
/**
* convert float into byte array using Float API floatToIntBits
* @param value
* @return byte[]
*/
public static byte[] floatToByteArray(float value) {
int intBits = Float.floatToIntBits(value);
return new byte[] {(byte) (intBits >> 24), (byte) (intBits >> 16), (byte) (intBits >> 8), (byte) (intBits) };
}
/**
* convert byte array into float using Float API intBitsToFloat
* @param bytes
* @return float
*/
public static float byteArrayToFloat(byte[] bytes) {
int intBits = bytes[0] << 24 | (bytes[1] & 0xFF) << 16 | (bytes[2] & 0xFF) << 8 | (bytes[3] & 0xFF);
return Float.intBitsToFloat(intBits);
}
/**
* convert float into byte array using ByteBuffer
* @param value
* @return byte[]
*/
public static byte[] floatToByteArrayWithByteBuffer(float value) {
return ByteBuffer.allocate(4).putFloat(value).array();
}
/**
* convert byte array into float using ByteBuffer
* @param bytes
* @return float
*/
public static float byteArrayToFloatWithByteBuffer(byte[] bytes) {
return ByteBuffer.wrap(bytes).getFloat();
}
}

View File

@@ -1,7 +1,216 @@
package com.baeldung.array.operations;
import org.apache.commons.lang3.ArrayUtils;
import java.lang.reflect.Array;
import java.util.*;
import java.util.function.Function;
import java.util.function.IntPredicate;
import java.util.function.Predicate;
import java.util.stream.Stream;
public class ArrayOperations {
// Get the first and last item of an array
public static <T> T getFirstObject(T[] array) {
return array[0];
}
public static int getFirstInt(int[] array) {
return array[0];
}
public static <T> T getLastObject(T[] array) {
return array[array.length - 1];
}
public static int getLastInt(int[] array) {
return array[array.length - 1];
}
// Append a new item to an array
public static <T> T[] appendObject(T[] array, T newItem) {
return ArrayUtils.add(array, newItem);
}
public static int[] appendInt(int[] array, int newItem) {
int[] newArray = Arrays.copyOf(array, array.length + 1);
newArray[newArray.length - 1] = newItem;
return newArray;
}
public static int[] appendIntWithUtils(int[] array, int newItem) {
return ArrayUtils.add(array, newItem);
}
// Compare two arrays to check if they have the same elements
public static <T> boolean compareObjectArrays(T[] array1, T[] array2) {
return Arrays.equals(array1, array2);
}
public static boolean compareIntArrays(int[] array1, int[] array2) {
return Arrays.equals(array1, array2);
}
// Deep Compare (for nested arrays)
public static <T> boolean deepCompareObjectArrayUsingArrays(T[][] array1, T[][] array2) {
// We can use Objects.deepEquals for a broader approach
return Arrays.deepEquals(array1, array2);
}
public static boolean deepCompareIntArrayUsingArrays(int[][] array1, int[][] array2) {
return Arrays.deepEquals(array1, array2);
}
// Check if array is empty
public static <T> boolean isEmptyObjectArrayUsingUtils(T[] array1) {
return ArrayUtils.isEmpty(array1);
}
public static boolean isEmptyIntArrayUsingUtils(int[] array1) {
return ArrayUtils.isEmpty(array1);
}
// Remove duplicates
public static Integer[] removeDuplicateObjects(Integer[] array) {
// We can use other ways of converting the array to a set too
Set<Integer> set = new HashSet<>(Arrays.asList(array));
return set.toArray(new Integer[set.size()]);
}
public static int[] removeDuplicateInts(int[] array) {
// Box
Integer[] list = ArrayUtils.toObject(array);
// Remove duplicates
Set<Integer> set = new HashSet<Integer>(Arrays.asList(list));
// Create array and unbox
return ArrayUtils.toPrimitive(set.toArray(new Integer[set.size()]));
}
// Remove duplicates preserving the order
public static Integer[] removeDuplicateWithOrderObjectArray(Integer[] array) {
// We can use other ways of converting the array to a set too
Set<Integer> set = new LinkedHashSet<>(Arrays.asList(array));
return set.toArray(new Integer[set.size()]);
}
public static int[] removeDuplicateWithOrderIntArray(int[] array) {
// Box
Integer[] list = ArrayUtils.toObject(array);
// Remove duplicates
Set<Integer> set = new LinkedHashSet<Integer>(Arrays.asList(list));
// Create array and unbox
return ArrayUtils.toPrimitive(set.toArray(new Integer[set.size()]));
}
// Print an array
public static String printObjectArray(Integer[] array) {
return ArrayUtils.toString(array);
}
public static String printObjectArray(Integer[][] array) {
return ArrayUtils.toString(array);
}
public static String printIntArray(int[] array) {
return ArrayUtils.toString(array);
}
public static String printIntArray(int[][] array) {
return ArrayUtils.toString(array);
}
// Box or Unbox values
public static int[] unboxIntegerArray(Integer[] array) {
return ArrayUtils.toPrimitive(array);
}
public static Integer[] boxIntArray(int[] array) {
return ArrayUtils.toObject(array);
}
// Map array values
@SuppressWarnings("unchecked")
public static <T, U> U[] mapObjectArray(T[] array, Function<T, U> function, Class<U> targetClazz) {
U[] newArray = (U[]) Array.newInstance(targetClazz, array.length);
for (int i = 0; i < array.length; i++) {
newArray[i] = function.apply(array[i]);
}
return newArray;
}
public static String[] mapIntArrayToString(int[] array) {
return Arrays.stream(array)
.mapToObj(value -> String.format("Value: %s", value))
.toArray(String[]::new);
}
// Filter array values
public static Integer[] filterObjectArray(Integer[] array, Predicate<Integer> predicate) {
return Arrays.stream(array)
.filter(predicate)
.toArray(Integer[]::new);
}
public static int[] filterIntArray(int[] array, IntPredicate predicate) {
return Arrays.stream(array)
.filter(predicate)
.toArray();
}
// Insert item between others
public static int[] insertBetweenIntArray(int[] array, int... values) {
return ArrayUtils.insert(2, array, values);
}
@SuppressWarnings("unchecked")
public static <T> T[] insertBetweenObjectArray(T[] array, T... values) {
return ArrayUtils.insert(2, array, values);
}
// Shuffling arrays
public static int[] shuffleIntArray(int[] array) {
// we create a different array instance for testing purposes
int[] shuffled = Arrays.copyOf(array, array.length);
ArrayUtils.shuffle(shuffled);
return shuffled;
}
public static <T> T[] shuffleObjectArray(T[] array) {
// we create a different array instance for testing purposes
T[] shuffled = Arrays.copyOf(array, array.length);
ArrayUtils.shuffle(shuffled);
return shuffled;
}
// Get random number
public static int getRandomFromIntArray(int[] array) {
return array[new Random().nextInt(array.length)];
}
public static <T> T getRandomFromObjectArray(T[] array) {
return array[new Random().nextInt(array.length)];
}
public static Integer[] intersectionSimple(final Integer[] a, final Integer[] b) {
return Stream.of(a)
.filter(Arrays.asList(b)::contains)
.toArray(Integer[]::new);
}
public static Integer[] intersectionSet(final Integer[] a, final Integer[] b) {
return Stream.of(a)
.filter(Arrays.asList(b)::contains)
.distinct()
.toArray(Integer[]::new);
}
public static Integer[] intersectionMultiSet(final Integer[] a, final Integer[] b) {
return Stream.of(a)
.filter(new LinkedList<>(Arrays.asList(b))::remove)
.toArray(Integer[]::new);
}
public static Integer[] addElementUsingPureJava(Integer[] srcArray, int elementToAdd) {
Integer[] destArray = new Integer[srcArray.length + 1];

View File

@@ -0,0 +1,49 @@
package com.baeldung.array;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertArrayEquals;
public class AddElementToEndOfArrayUnitTest {
AddElementToEndOfArray addElementToEndOfArray;
@Before
public void init() {
addElementToEndOfArray = new AddElementToEndOfArray();
}
@Test
public void givenSourceArrayAndElement_whenAddElementUsingArraysCopyIsInvoked_thenNewElementMustBeAdded() {
Integer[] sourceArray = {1, 2, 3, 4};
int elementToAdd = 5;
Integer[] destArray = addElementToEndOfArray.addElementUsingArraysCopyOf(sourceArray, elementToAdd);
Integer[] expectedArray = {1, 2, 3, 4, 5};
assertArrayEquals(expectedArray, destArray);
}
@Test
public void givenSourceArrayAndElement_whenAddElementUsingArrayListIsInvoked_thenNewElementMustBeAdded() {
Integer[] sourceArray = {1, 2, 3, 4};
int elementToAdd = 5;
Integer[] destArray = addElementToEndOfArray.addElementUsingArrayList(sourceArray, elementToAdd);
Integer[] expectedArray = {1, 2, 3, 4, 5};
assertArrayEquals(expectedArray, destArray);
}
@Test
public void givenSourceArrayAndElement_whenAddElementUsingSystemArrayCopyIsInvoked_thenNewElementMustBeAdded() {
Integer[] sourceArray = {1, 2, 3, 4};
int elementToAdd = 5;
Integer[] destArray = addElementToEndOfArray.addElementUsingSystemArrayCopy(sourceArray, elementToAdd);
Integer[] expectedArray = {1, 2, 3, 4, 5};
assertArrayEquals(expectedArray, destArray);
}
}

View File

@@ -0,0 +1,82 @@
package com.baeldung.array;
import org.apache.commons.lang3.ArrayUtils;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class RemoveElementFromAnArrayUnitTest {
private final RemoveElementFromAnArray sut = new RemoveElementFromAnArray();
private final int[] inputArray = new int[] { 40, 10, 20, 30, 40, 50 };
@Test
void testRemoveAnElementWithAGivenIndex() {
int index = 2;
int[] modifiedArray = sut.removeAnElementWithAGivenIndex(inputArray, index);
assertFalse(ArrayUtils.contains(modifiedArray, inputArray[index]));
}
@Test
void testRemoveAllElementsWithGivenIndices() {
int first = 0;
int last = inputArray.length - 1;
int[] modifiedArray = sut.removeAllElementsWithGivenIndices(inputArray, first, last);
assertFalse(ArrayUtils.contains(modifiedArray, inputArray[first]) && ArrayUtils.contains(modifiedArray, inputArray[last]));
}
@Test
void testRemoveElement_WhenArrayIsNull_ThrowsIndexOutOfBoundEx() {
int index = 2;
assertThrows(IndexOutOfBoundsException.class, () -> {
sut.removeAnElementWithAGivenIndex(null, index);
});
assertThrows(IndexOutOfBoundsException.class, () -> {
sut.removeAllElementsWithGivenIndices(null, index);
});
}
@Test
void testRemoveFirstOccurrenceOfGivenElement() {
int element = 40;
int[] modifiedArray = sut.removeFirstOccurrenceOfGivenElement(inputArray, element);
int indexInInputArray = ArrayUtils.indexOf(inputArray, element);
int indexInModifiedArray = ArrayUtils.indexOf(modifiedArray, element);
assertFalse(indexInInputArray == indexInModifiedArray);
}
@Test
void testRemoveAllGivenElements() {
int duplicateElement = 40;
int[] elements = new int[] { duplicateElement, 10, 50 };
int[] modifiedArray = sut.removeAllGivenElements(inputArray, elements);
assertTrue(ArrayUtils.contains(modifiedArray, duplicateElement));
assertFalse(ArrayUtils.contains(modifiedArray, elements[1]));
assertFalse(ArrayUtils.contains(modifiedArray, elements[2]));
}
@Test
void testRemoveAllOccurrencesOfAGivenElement() {
int element = 40;
int[] modifiedArray = sut.removeAllOccurrencesOfAGivenElement(inputArray, element);
assertFalse(ArrayUtils.contains(modifiedArray, element));
}
@Test
void testRemoveElement_WhenArrayIsNull_ReturnsNull() {
int element = 20;
assertEquals(null, sut.removeFirstOccurrenceOfGivenElement(null, element));
assertEquals(null, sut.removeAllGivenElements(null, element));
assertEquals(null, sut.removeAllOccurrencesOfAGivenElement(null, element));
}
}

View File

@@ -0,0 +1,44 @@
package com.baeldung.array.conversions;
import org.junit.Test;
import static com.baeldung.array.conversions.FloatToByteArray.*;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
public class FloatToByteArrayUnitTest {
@Test
public void givenAFloat_thenConvertToByteArray() {
assertArrayEquals(new byte[] { 63, -116, -52, -51}, floatToByteArray(1.1f));
}
@Test
public void givenAByteArray_thenConvertToFloat() {
assertEquals(1.1f, byteArrayToFloat(new byte[] { 63, -116, -52, -51}), 0);
}
@Test
public void givenAFloat_thenConvertToByteArrayUsingByteBuffer() {
assertArrayEquals(new byte[] { 63, -116, -52, -51}, floatToByteArrayWithByteBuffer(1.1f));
}
@Test
public void givenAByteArray_thenConvertToFloatUsingByteBuffer() {
assertEquals(1.1f, byteArrayToFloatWithByteBuffer(new byte[] { 63, -116, -52, -51}), 0);
}
@Test
public void givenAFloat_thenConvertToByteArray_thenConvertToFloat() {
float floatToConvert = 200.12f;
byte[] byteArray = floatToByteArray(floatToConvert);
assertEquals(200.12f, byteArrayToFloat(byteArray), 0);
}
@Test
public void givenAFloat_thenConvertToByteArrayWithByteBuffer_thenConvertToFloatWithByteBuffer() {
float floatToConvert = 30100.42f;
byte[] byteArray = floatToByteArrayWithByteBuffer(floatToConvert);
assertEquals(30100.42f, byteArrayToFloatWithByteBuffer(byteArray), 0);
}
}

View File

@@ -1,11 +1,360 @@
package com.baeldung.array.operations;
import java.util.Arrays;
import org.assertj.core.api.Condition;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.Assert.assertArrayEquals;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertArrayEquals;
public class ArrayOperationsUnitTest {
private Integer[] defaultObjectArray;
private int[] defaultIntArray;
private Integer[][] defaultJaggedObjectArray;
private int[][] defaultJaggedIntArray;
@BeforeEach
public void setupDefaults() {
defaultObjectArray = new Integer[] { 3, 5, 2, 5, 14, 4 };
defaultIntArray = new int[] { 3, 5, 2, 5, 14, 4 };
defaultJaggedObjectArray = new Integer[][] { { 1, 3 }, { 5 }, {} };
defaultJaggedIntArray = new int[][] { { 1, 3 }, { 5 }, {} };
}
// Get the first and last item of an array
@Test
public void whenGetFirstObjectCalled_thenReturnFirstItemOfArray() {
Integer output = ArrayOperations.getFirstObject(defaultObjectArray);
assertThat(output).isEqualTo(3);
}
@Test
public void whenGetFirstIntCalled_thenReturnFirstItemOfArray() {
int output = ArrayOperations.getFirstInt(defaultIntArray);
assertThat(output).isEqualTo(3);
}
@Test
public void whenGetLastObjectCalled_thenReturnLastItemOfArray() {
Integer output = ArrayOperations.getLastObject(defaultObjectArray);
assertThat(output).isEqualTo(4);
}
@Test
public void whenGetLastIntCalled_thenReturnLastItemOfArray() {
int output = ArrayOperations.getLastInt(defaultIntArray);
assertThat(output).isEqualTo(4);
}
// Append a new item to an array
@Test
public void whenAppendObject_thenReturnArrayWithExtraItem() {
Integer[] output = ArrayOperations.appendObject(defaultObjectArray, 7);
assertThat(output).endsWith(4, 7)
.hasSize(7);
}
@Test
public void whenAppendInt_thenReturnArrayWithExtraItem() {
int[] output = ArrayOperations.appendInt(defaultIntArray, 7);
int[] outputUsingUtils = ArrayOperations.appendIntWithUtils(defaultIntArray, 7);
assertThat(output).endsWith(4, 7)
.hasSize(7);
assertThat(outputUsingUtils).endsWith(4, 7)
.hasSize(7);
}
// Compare two arrays to check if they have the same elements
@Test
public void whenCompareObjectArrays_thenReturnBoolean() {
Integer[] array2 = { 8, 7, 6 };
Integer[] sameArray = { 3, 5, 2, 5, 14, 4 };
boolean output = ArrayOperations.compareObjectArrays(defaultObjectArray, array2);
boolean output2 = ArrayOperations.compareObjectArrays(defaultObjectArray, sameArray);
assertThat(output).isFalse();
assertThat(output2).isTrue();
}
@Test
public void whenCompareIntArrays_thenReturnBoolean() {
int[] array2 = { 8, 7, 6 };
int[] sameArray = { 3, 5, 2, 5, 14, 4 };
boolean output = ArrayOperations.compareIntArrays(defaultIntArray, array2);
boolean output2 = ArrayOperations.compareIntArrays(defaultIntArray, sameArray);
assertThat(output).isFalse();
assertThat(output2).isTrue();
}
// Deep compare
@Test
public void whenDeepCompareObjectArrays_thenReturnBoolean() {
Integer[][] sameArray = { { 1, 3 }, { 5 }, {} };
Integer[][] array2 = { { 1, 3 }, { 5 }, { 3 } };
boolean output = ArrayOperations.deepCompareObjectArrayUsingArrays(defaultJaggedObjectArray, array2);
boolean output2 = ArrayOperations.deepCompareObjectArrayUsingArrays(defaultJaggedObjectArray, sameArray);
// Because arrays are Objects, we could wrongly use the non-deep approach
boolean outputUsingNonDeep = ArrayOperations.compareObjectArrays(defaultJaggedObjectArray, sameArray);
assertThat(output).isFalse();
assertThat(output2).isTrue();
// This is not what we would expect!
assertThat(outputUsingNonDeep).isFalse();
}
@Test
public void whenDeepCompareIntArrays_thenReturnBoolean() {
int[][] sameArray = { { 1, 3 }, { 5 }, {} };
int[][] array2 = { { 1, 3 }, { 5 }, { 3 } };
boolean output = ArrayOperations.deepCompareIntArrayUsingArrays(defaultJaggedIntArray, array2);
boolean output2 = ArrayOperations.deepCompareIntArrayUsingArrays(defaultJaggedIntArray, sameArray);
assertThat(output).isFalse();
assertThat(output2).isTrue();
}
// Empty Check
@Test
public void whenIsEmptyObjectArray_thenReturnBoolean() {
Integer[] array2 = {};
Integer[] array3 = null;
Integer[] array4 = { null, null, null };
Integer[] array5 = { null };
Integer[][] array6 = { {}, {}, {} };
boolean output = ArrayOperations.isEmptyObjectArrayUsingUtils(defaultObjectArray);
boolean output2 = ArrayOperations.isEmptyObjectArrayUsingUtils(array2);
boolean output3 = ArrayOperations.isEmptyObjectArrayUsingUtils(array3);
boolean output4 = ArrayOperations.isEmptyObjectArrayUsingUtils(array4);
boolean output5 = ArrayOperations.isEmptyObjectArrayUsingUtils(array5);
boolean output6 = ArrayOperations.isEmptyObjectArrayUsingUtils(array6);
assertThat(output).isFalse();
assertThat(output2).isTrue();
assertThat(output3).isTrue();
// Mind these edge cases!
assertThat(output4).isFalse();
assertThat(output5).isFalse();
assertThat(output6).isFalse();
}
@Test
public void whenIsEmptyIntArray_thenReturnBoolean() {
int[] array2 = {};
boolean output = ArrayOperations.isEmptyIntArrayUsingUtils(defaultIntArray);
boolean output2 = ArrayOperations.isEmptyIntArrayUsingUtils(array2);
assertThat(output).isFalse();
assertThat(output2).isTrue();
}
// Remove Duplicates
@Test
public void whenRemoveDuplicateObjectArray_thenReturnArrayWithNoDuplicates() {
Integer[] output = ArrayOperations.removeDuplicateObjects(defaultObjectArray);
assertThat(output).containsOnlyOnce(5)
.hasSize(5)
.doesNotHaveDuplicates();
}
@Test
public void whenRemoveDuplicateIntArray_thenReturnArrayWithNoDuplicates() {
int[] output = ArrayOperations.removeDuplicateInts(defaultIntArray);
assertThat(output).containsOnlyOnce(5)
.hasSize(5)
.doesNotHaveDuplicates();
}
// Remove Duplicates Preserving order
@Test
public void whenRemoveDuplicatePreservingOrderObjectArray_thenReturnArrayWithNoDuplicates() {
Integer[] array2 = { 3, 5, 2, 14, 4 };
Integer[] output = ArrayOperations.removeDuplicateWithOrderObjectArray(defaultObjectArray);
assertThat(output).containsOnlyOnce(5)
.hasSize(5)
.containsExactly(array2);
}
@Test
public void whenRemoveDuplicatePreservingOrderIntArray_thenReturnArrayWithNoDuplicates() {
int[] array2 = { 3, 5, 2, 14, 4 };
int[] output = ArrayOperations.removeDuplicateWithOrderIntArray(defaultIntArray);
assertThat(output).containsOnlyOnce(5)
.hasSize(5)
.containsExactly(array2);
}
// Print
@Test
public void whenPrintObjectArray_thenReturnString() {
String output = ArrayOperations.printObjectArray(defaultObjectArray);
String jaggedOutput = ArrayOperations.printObjectArray(defaultJaggedObjectArray);
// Comparing to Arrays output:
String wrongArraysOutput = Arrays.toString(defaultJaggedObjectArray);
String differentFormatArraysOutput = Arrays.toString(defaultObjectArray);
// We should use Arrays.deepToString for jagged arrays
String differentFormatJaggedArraysOutput = Arrays.deepToString(defaultJaggedObjectArray);
assertThat(output).isEqualTo("{3,5,2,5,14,4}");
assertThat(jaggedOutput).isEqualTo("{{1,3},{5},{}}");
assertThat(differentFormatArraysOutput).isEqualTo("[3, 5, 2, 5, 14, 4]");
assertThat(wrongArraysOutput).contains("[[Ljava.lang.Integer;@");
assertThat(differentFormatJaggedArraysOutput).contains("[[1, 3], [5], []]");
}
@Test
public void whenPrintIntArray_thenReturnString() {
String output = ArrayOperations.printIntArray(defaultIntArray);
String jaggedOutput = ArrayOperations.printIntArray(defaultJaggedIntArray);
// Comparing to Arrays output:
String wrongArraysOutput = Arrays.toString(defaultJaggedObjectArray);
String differentFormatArraysOutput = Arrays.toString(defaultObjectArray);
assertThat(output).isEqualTo("{3,5,2,5,14,4}");
assertThat(jaggedOutput).isEqualTo("{{1,3},{5},{}}");
assertThat(differentFormatArraysOutput).isEqualTo("[3, 5, 2, 5, 14, 4]");
assertThat(wrongArraysOutput).contains("[[Ljava.lang.Integer;@");
}
// Box and unbox
@Test
public void whenUnboxObjectArray_thenReturnPrimitiveArray() {
int[] output = ArrayOperations.unboxIntegerArray(defaultObjectArray);
assertThat(output).containsExactly(defaultIntArray);
}
@Test
public void henBoxPrimitiveArray_thenReturnObjectArray() {
Integer[] output = ArrayOperations.boxIntArray(defaultIntArray);
assertThat(output).containsExactly(defaultObjectArray);
}
// Map values
@Test
public void whenMapMultiplyingObjectArray_thenReturnMultipliedArray() {
Integer[] multipliedExpectedArray = new Integer[] { 6, 10, 4, 10, 28, 8 };
Integer[] output = ArrayOperations.mapObjectArray(defaultObjectArray, value -> value * 2, Integer.class);
assertThat(output).containsExactly(multipliedExpectedArray);
}
@Test
public void whenMapDividingObjectArray_thenReturnDividedArray() {
Double[] multipliedExpectedArray = new Double[] { 1.5, 2.5, 1.0, 2.5, 7.0, 2.0 };
Double[] output = ArrayOperations.mapObjectArray(defaultObjectArray, value -> value / 2.0, Double.class);
assertThat(output).containsExactly(multipliedExpectedArray);
}
@Test
public void whenMapIntArrayToString_thenReturnArray() {
String[] expectedArray = new String[] { "Value: 3", "Value: 5", "Value: 2", "Value: 5", "Value: 14", "Value: 4" };
String[] output = ArrayOperations.mapIntArrayToString(defaultIntArray);
assertThat(output).containsExactly(expectedArray);
}
// Filter values
@Test
public void whenFilterObjectArray_thenReturnFilteredArray() {
Integer[] multipliedExpectedArray = new Integer[] { 2, 14, 4 };
Integer[] output = ArrayOperations.filterObjectArray(defaultObjectArray, value -> value % 2 == 0);
assertThat(output).containsExactly(multipliedExpectedArray);
}
@Test
public void whenFilterIntArray_thenReturnFilteredArray() {
int[] expectedArray = new int[] { 2, 14, 4 };
int[] output = ArrayOperations.filterIntArray(defaultIntArray, value -> (int) value % 2 == 0);
assertThat(output).containsExactly(expectedArray);
}
// Insert between
@Test
public void whenInsertBetweenIntArrayToString_thenReturnNewArray() {
int[] expectedArray = { 3, 5, 77, 88, 2, 5, 14, 4 };
int[] output = ArrayOperations.insertBetweenIntArray(defaultIntArray, 77, 88);
assertThat(output).containsExactly(expectedArray);
}
@Test
public void whenInsertBetweenObjectArrayToString_thenReturnNewArray() {
Integer[] expectedArray = { 3, 5, 77, 99, 2, 5, 14, 4 };
Integer[] output = ArrayOperations.insertBetweenObjectArray(defaultObjectArray, 77, 99);
assertThat(output).containsExactly(expectedArray);
}
// Shuffle between
@Test
public void whenShufflingIntArraySeveralTimes_thenAtLeastOneWithDifferentOrder() {
int[] output = ArrayOperations.shuffleIntArray(defaultIntArray);
int[] output2 = ArrayOperations.shuffleIntArray(defaultIntArray);
int[] output3 = ArrayOperations.shuffleIntArray(defaultIntArray);
int[] output4 = ArrayOperations.shuffleIntArray(defaultIntArray);
int[] output5 = ArrayOperations.shuffleIntArray(defaultIntArray);
int[] output6 = ArrayOperations.shuffleIntArray(defaultIntArray);
Condition<int[]> atLeastOneArraysIsNotEqual = new Condition<int[]>("at least one output should be different (order-wise)") {
@Override
public boolean matches(int[] value) {
return !Arrays.equals(value, output) || !Arrays.equals(value, output2) || !Arrays.equals(value, output3) || !Arrays.equals(value, output4) || !Arrays.equals(value, output5) || !Arrays.equals(value, output6);
}
};
assertThat(defaultIntArray).has(atLeastOneArraysIsNotEqual);
}
@Test
public void whenShufflingObjectArraySeveralTimes_thenAtLeastOneWithDifferentOrder() {
Integer[] output = ArrayOperations.shuffleObjectArray(defaultObjectArray);
Integer[] output2 = ArrayOperations.shuffleObjectArray(defaultObjectArray);
Integer[] output3 = ArrayOperations.shuffleObjectArray(defaultObjectArray);
Integer[] output4 = ArrayOperations.shuffleObjectArray(defaultObjectArray);
Integer[] output5 = ArrayOperations.shuffleObjectArray(defaultObjectArray);
Integer[] output6 = ArrayOperations.shuffleObjectArray(defaultObjectArray);
Condition<Integer[]> atLeastOneArraysIsNotEqual = new Condition<Integer[]>("at least one output should be different (order-wise)") {
@Override
public boolean matches(Integer[] value) {
return !Arrays.equals(value, output) || !Arrays.equals(value, output2) || !Arrays.equals(value, output3) || !Arrays.equals(value, output4) || !Arrays.equals(value, output5) || !Arrays.equals(value, output6);
}
};
assertThat(defaultObjectArray).has(atLeastOneArraysIsNotEqual);
}
// Get random item
@Test
public void whenGetRandomFromIntArrayToString_thenReturnItemContainedInArray() {
int output = ArrayOperations.getRandomFromIntArray(defaultIntArray);
assertThat(defaultIntArray).contains(output);
}
@Test
public void whenGetRandomFromObjectArrayToString_thenReturnItemContainedInArray() {
Integer output = ArrayOperations.getRandomFromObjectArray(defaultObjectArray);
assertThat(defaultObjectArray).contains(output);
}
@Test
public void givenSourceArrayAndElement_whenAddElementUsingPureJavaIsInvoked_thenNewElementMustBeAdded() {
Integer[] sourceArray = { 1, 2, 3, 4 };
@@ -28,5 +377,4 @@ public class ArrayOperationsUnitTest {
assertThat(outputArray).containsExactly(expectedArray);
}
}

View File

@@ -0,0 +1,64 @@
package com.baeldung.array.operations;
import org.junit.jupiter.api.Test;
import static com.baeldung.array.operations.ArrayOperations.*;
import static org.assertj.core.api.Assertions.assertThat;
class IntersectionUnitTest {
private static final Integer[] a = { 1, 3, 2 };
private static final Integer[] b = { 4, 3, 2, 4, 2, 3, 4, 4, 3 };
private static final Integer[] c = { 1, 3, 2, 3, 3, 2 };
@Test
void whenIntersectionSimpleIsUsed_thenCommonEntriesAreInTheResult() {
assertThat(intersectionSimple(a, b)).isEqualTo(new Integer[] { 3, 2 });
assertThat(intersectionSimple(b, a)).isEqualTo(new Integer[] { 3, 2, 2, 3, 3 });
}
@Test
void whenIntersectionSimpleIsUsedWithAnArrayAndItself_thenTheResultIsTheIdentity() {
assertThat(intersectionSimple(b, b)).isEqualTo(b);
assertThat(intersectionSimple(a, a)).isEqualTo(a);
}
@Test
void whenIntersectionSetIsUsed_thenCommonEntriesAreInTheResult() {
assertThat(intersectionSet(b, a)).isEqualTo(new Integer[] { 3, 2 });
}
@Test
void whenIntersectionSetIsUsed_thenTheNumberOfEntriesDoesNotChangeWithTheParameterOrder() {
assertThat(intersectionSet(a, b)).isEqualTo(new Integer[] { 3, 2 });
assertThat(intersectionSet(b, a)).isEqualTo(new Integer[] { 3, 2 });
}
@Test
void whenIntersectionSetIsUsedWithAnArrayAndWithItself_andTheInputHasNoDuplicateEntries_ThenTheResultIsTheIdentity() {
assertThat(intersectionSet(a, a)).isEqualTo(a);
}
@Test
void whenIntersectionSetIsUsedWithAnArrayAndWithItself_andTheInputHasDuplicateEntries_ThenTheResultIsNotTheIdentity() {
assertThat(intersectionSet(b, b)).isNotEqualTo(b);
}
@Test
void whenMultiSetIsUsed_thenCommonEntriesAreInTheResult() {
assertThat(intersectionMultiSet(b, a)).isEqualTo(new Integer[] { 3, 2 });
}
@Test
void whenIntersectionMultiSetIsUsed_thenTheNumberOfEntriesDoesNotChangeWithTheParameterOrder() {
assertThat(intersectionMultiSet(a, b)).isEqualTo(new Integer[] { 3, 2 });
assertThat(intersectionMultiSet(b, a)).isEqualTo(new Integer[] { 3, 2 });
assertThat(intersectionMultiSet(b, c)).isEqualTo(new Integer[] { 3, 2, 2, 3, 3 });
assertThat(intersectionMultiSet(c, b)).isEqualTo(new Integer[] { 3, 2, 3, 3, 2 });
}
@Test
void whenIntersectionMultiSetIsUsedWithAnArrayAndWithItself_ThenTheResultIsTheIdentity() {
assertThat(intersectionMultiSet(b, b)).isEqualTo(b);
assertThat(intersectionMultiSet(a, a)).isEqualTo(a);
}
}

View File

@@ -0,0 +1,62 @@
package com.baeldung.array.removefirst;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
public class RemoveFirstElementUnitTest {
private List<String> list = new ArrayList<>();
private LinkedList<String> linkedList = new LinkedList<>();
@Before
public void init() {
list.add("cat");
list.add("dog");
list.add("pig");
list.add("cow");
list.add("goat");
linkedList.add("cat");
linkedList.add("dog");
linkedList.add("pig");
linkedList.add("cow");
linkedList.add("goat");
}
@Test
public void givenList_whenRemoveFirst_thenRemoved() {
list.remove(0);
assertThat(list, hasSize(4));
assertThat(list, not(contains("cat")));
}
@Test
public void givenLinkedList_whenRemoveFirst_thenRemoved() {
linkedList.removeFirst();
assertThat(linkedList, hasSize(4));
assertThat(linkedList, not(contains("cat")));
}
@Test
public void givenStringArray_whenRemovingFirstElement_thenArrayIsSmallerAndElementRemoved() {
String[] stringArray = {"foo", "bar", "baz"};
String[] modifiedArray = Arrays.copyOfRange(stringArray, 1, stringArray.length);
assertThat(modifiedArray.length, is(2));
assertThat(modifiedArray[0], is("bar"));
}
}