[BAEL-9555] - Created a core-java-modules folder

This commit is contained in:
amit2103
2019-05-05 17:22:09 +05:30
parent 8b63b0d90a
commit 3bae5e5334
1480 changed files with 25600 additions and 5594 deletions

View File

@@ -0,0 +1,25 @@
*.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

@@ -0,0 +1,17 @@
=========
## Core Java Arrays Cookbooks and Examples
### Relevant Articles:
- [How to Copy an Array in Java](http://www.baeldung.com/java-array-copy)
- [Check if a Java Array Contains a Value](http://www.baeldung.com/java-array-contains-value)
- [Initializing Arrays in Java](http://www.baeldung.com/java-initialize-array)
- [Guide to the java.util.Arrays Class](http://www.baeldung.com/java-util-arrays)
- [Jagged Arrays In Java](http://www.baeldung.com/java-jagged-arrays)
- [Find Sum and Average in a Java Array](http://www.baeldung.com/java-array-sum-average)
- [Arrays in Java: A Reference Guide](https://www.baeldung.com/java-arrays-guide)
- [How to Invert an Array in Java](http://www.baeldung.com/java-invert-array)
- [Array Operations in Java](http://www.baeldung.com/java-common-array-operations)
- [Intersection Between two Integer Arrays](https://www.baeldung.com/java-array-intersection)
- [Sorting Arrays in Java](https://www.baeldung.com/java-sorting-arrays)
- [Convert a Float to a Byte Array in Java](https://www.baeldung.com/java-convert-float-to-byte-array)

View File

@@ -0,0 +1,411 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>core-java-arrays</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-arrays</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-java</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency> <!-- needed to bridge to slf4j for projects that use the log4j APIs directly -->
<groupId>org.slf4j</groupId>
<artifactId>log4j-over-slf4j</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<!-- test scoped -->
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj-core.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>${jmh-core.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>${jmh-generator-annprocess.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${springframework.spring-web.version}</version>
</dependency>
</dependencies>
<build>
<finalName>core-java-arrays</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<excludes>
<exclude>**/*LiveTest.java</exclude>
<exclude>**/*IntegrationTest.java</exclude>
<exclude>**/*IntTest.java</exclude>
<exclude>**/*LongRunningUnitTest.java</exclude>
<exclude>**/*ManualTest.java</exclude>
</excludes>
<testFailureIgnore>true</testFailureIgnore>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>copy-dependencies</id>
<phase>prepare-package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/libs</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>${maven-jar-plugin.version}</version>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<classpathPrefix>libs/</classpathPrefix>
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
<configuration>
<archiveBaseDirectory>${project.basedir}</archiveBaseDirectory>
<archive>
<manifest>
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>${maven-shade-plugin.version}</version>
<executions>
<execution>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<shadedArtifactAttached>true</shadedArtifactAttached>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>com.jolira</groupId>
<artifactId>onejar-maven-plugin</artifactId>
<version>${onejar-maven-plugin.version}</version>
<executions>
<execution>
<configuration>
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
<attachToBuild>true</attachToBuild>
<filename>${project.build.finalName}-onejar.${project.packaging}</filename>
</configuration>
<goals>
<goal>one-jar</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>${spring-boot-maven-plugin.version}</version>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
<configuration>
<classifier>spring-boot</classifier>
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>${exec-maven-plugin.version}</version>
<configuration>
<executable>java</executable>
<mainClass>com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed</mainClass>
<arguments>
<argument>-Xmx300m</argument>
<argument>-XX:+UseParallelGC</argument>
<argument>-classpath</argument>
<classpath />
<argument>com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed</argument>
</arguments>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>${maven-javadoc-plugin.version}</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>integration</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<executions>
<execution>
<phase>integration-test</phase>
<goals>
<goal>test</goal>
</goals>
<configuration>
<excludes>
<exclude>**/*ManualTest.java</exclude>
</excludes>
<includes>
<include>**/*IntegrationTest.java</include>
<include>**/*IntTest.java</include>
</includes>
</configuration>
</execution>
</executions>
<configuration>
<systemPropertyVariables>
<test.mime>json</test.mime>
</systemPropertyVariables>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>${exec-maven-plugin.version}</version>
<executions>
<execution>
<id>run-benchmarks</id>
<!-- <phase>integration-test</phase> -->
<phase>none</phase>
<goals>
<goal>exec</goal>
</goals>
<configuration>
<classpathScope>test</classpathScope>
<executable>java</executable>
<arguments>
<argument>-classpath</argument>
<classpath />
<argument>org.openjdk.jmh.Main</argument>
<argument>.*</argument>
</arguments>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
<!-- java instrumentation profiles to build jars -->
<profile>
<id>buildAgentLoader</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>jar</goal>
</goals>
<configuration>
<classifier>agentLoader</classifier>
<classesDirectory>target/classes</classesDirectory>
<archive>
<manifest>
<addClasspath>true</addClasspath>
</manifest>
<manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
</archive>
<includes>
<include>com/baeldung/instrumentation/application/AgentLoader.class</include>
<include>com/baeldung/instrumentation/application/Launcher.class</include>
</includes>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>buildApplication</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>jar</goal>
</goals>
<configuration>
<classifier>application</classifier>
<classesDirectory>target/classes</classesDirectory>
<archive>
<manifest>
<addClasspath>true</addClasspath>
</manifest>
<manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
</archive>
<includes>
<include>com/baeldung/instrumentation/application/MyAtm.class</include>
<include>com/baeldung/instrumentation/application/MyAtmApplication.class</include>
<include>com/baeldung/instrumentation/application/Launcher.class</include>
</includes>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>buildAgent</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>jar</goal>
</goals>
<configuration>
<classifier>agent</classifier>
<classesDirectory>target/classes</classesDirectory>
<archive>
<manifest>
<addClasspath>true</addClasspath>
</manifest>
<manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
</archive>
<includes>
<include>com/baeldung/instrumentation/agent/AtmTransformer.class</include>
<include>com/baeldung/instrumentation/agent/MyInstrumentationAgent.class</include>
</includes>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<properties>
<!-- util -->
<commons-lang3.version>3.8.1</commons-lang3.version>
<jmh-core.version>1.19</jmh-core.version>
<jmh-generator-annprocess.version>1.19</jmh-generator-annprocess.version>
<!-- testing -->
<assertj-core.version>3.10.0</assertj-core.version>
<!-- maven and spring plugins -->
<maven-surefire-plugin.version>2.21.0</maven-surefire-plugin.version>
<springframework.spring-web.version>4.3.4.RELEASE</springframework.spring-web.version>
<maven-javadoc-plugin.version>3.0.0-M1</maven-javadoc-plugin.version>
<maven-jar-plugin.version>3.0.2</maven-jar-plugin.version>
<onejar-maven-plugin.version>1.4.4</onejar-maven-plugin.version>
<maven-shade-plugin.version>3.1.1</maven-shade-plugin.version>
<spring-boot-maven-plugin.version>2.0.3.RELEASE</spring-boot-maven-plugin.version>
<exec-maven-plugin.version>1.6.0</exec-maven-plugin.version>
</properties>
</project>

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,21 @@
package com.baeldung.array;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
public class ArrayBenchmarkRunner {
public static void main(String[] args) throws Exception {
Options options = new OptionsBuilder()
.include(SearchArrayUnitTest.class.getSimpleName()).threads(1)
.forks(1).shouldFailOnError(true).shouldDoGC(true)
.jvmArgs("-server").build();
new Runner(options).run();
}
}

View File

@@ -0,0 +1,78 @@
package com.baeldung.array;
import java.util.Arrays;
import org.apache.commons.lang3.ArrayUtils;
public class ArrayInitializer {
static int[] initializeArrayInLoop() {
int array[] = new int[5];
for (int i = 0; i < array.length; i++) {
array[i] = i + 2;
}
return array;
}
static int[][] initializeMultiDimensionalArrayInLoop() {
int array[][] = new int[2][5];
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 5; j++) {
array[i][j] = j + 1;
}
}
return array;
}
static String[] initializeArrayAtTimeOfDeclarationMethod1() {
String array[] = new String[] { "Toyota", "Mercedes", "BMW", "Volkswagen", "Skoda" };
return array;
}
static int[] initializeArrayAtTimeOfDeclarationMethod2() {
int[] array = new int[] { 1, 2, 3, 4, 5 };
return array;
}
static int[] initializeArrayAtTimeOfDeclarationMethod3() {
int array[] = { 1, 2, 3, 4, 5 };
return array;
}
static long[] initializeArrayUsingArraysFill() {
long array[] = new long[5];
Arrays.fill(array, 30);
return array;
}
static int[] initializeArrayRangeUsingArraysFill() {
int array[] = new int[5];
Arrays.fill(array, 0, 3, -50);
return array;
}
static int[] initializeArrayUsingArraysCopy() {
int array[] = { 1, 2, 3, 4, 5 };
int[] copy = Arrays.copyOf(array, 5);
return copy;
}
static int[] initializeLargerArrayUsingArraysCopy() {
int array[] = { 1, 2, 3, 4, 5 };
int[] copy = Arrays.copyOf(array, 6);
return copy;
}
static int[] initializeArrayUsingArraysSetAll() {
int[] array = new int[20];
Arrays.setAll(array, p -> p > 9 ? 0 : p);
return array;
}
static char[] initializeArrayUsingArraysUtilClone() {
char[] array = new char[] { 'a', 'b', 'c' };
return ArrayUtils.clone(array);
}
}

View File

@@ -0,0 +1,43 @@
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.rangeClosed(1, array.length)
.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,159 @@
package com.baeldung.array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class ArrayReferenceGuide {
public static void main(String[] args) {
declaration();
initialization();
access();
iterating();
varargs();
transformIntoList();
transformIntoStream();
sort();
search();
merge();
}
private static void declaration() {
int[] anArray;
int anotherArray[];
}
private static void initialization() {
int[] anArray = new int[10];
anArray[0] = 10;
anArray[5] = 4;
int[] anotherArray = new int[] {1, 2, 3, 4, 5};
}
private static void access() {
int[] anArray = new int[10];
anArray[0] = 10;
anArray[5] = 4;
System.out.println(anArray[0]);
}
private static void iterating() {
int[] anArray = new int[] {1, 2, 3, 4, 5};
for (int i = 0; i < anArray.length; i++) {
System.out.println(anArray[i]);
}
for (int element : anArray) {
System.out.println(element);
}
}
private static void varargs() {
String[] groceries = new String[] {"Milk", "Tomato", "Chips"};
varargMethod(groceries);
varargMethod("Milk", "Tomato", "Chips");
}
private static void varargMethod(String... varargs) {
for (String element : varargs) {
System.out.println(element);
}
}
private static void transformIntoList() {
Integer[] anArray = new Integer[] {1, 2, 3, 4, 5};
// Naïve implementation
List<Integer> aList = new ArrayList<>(); // We create an empty list
for (int element : anArray) {
// We iterate over array's elements and add them to the list
aList.add(element);
}
// Pretty implementation
aList = Arrays.asList(anArray);
// Drawbacks
try {
aList.remove(0);
} catch (UnsupportedOperationException e) {
System.out.println(e.getMessage());
}
try {
aList.add(6);
} catch (UnsupportedOperationException e) {
System.out.println(e.getMessage());
}
int[] anotherArray = new int[] {1, 2, 3, 4, 5};
// List<Integer> anotherList = Arrays.asList(anotherArray);
}
private static void transformIntoStream() {
int[] anArray = new int[] {1, 2, 3, 4, 5};
IntStream aStream = Arrays.stream(anArray);
Integer[] anotherArray = new Integer[] {1, 2, 3, 4, 5};
Stream<Integer> anotherStream = Arrays.stream(anotherArray, 2, 4);
}
private static void sort() {
int[] anArray = new int[] {5, 2, 1, 4, 8};
Arrays.sort(anArray); // anArray is now {1, 2, 4, 5, 8}
Integer[] anotherArray = new Integer[] {5, 2, 1, 4, 8};
Arrays.sort(anotherArray); // anArray is now {1, 2, 4, 5, 8}
String[] yetAnotherArray = new String[] {"A", "E", "Z", "B", "C"};
Arrays.sort(yetAnotherArray, 1, 3, Comparator.comparing(String::toString).reversed()); // yetAnotherArray is now {"A", "Z", "E", "B", "C"}
}
private static void search() {
int[] anArray = new int[] {5, 2, 1, 4, 8};
for (int i = 0; i < anArray.length; i++) {
if (anArray[i] == 4) {
System.out.println("Found at index " + i);
break;
}
}
Arrays.sort(anArray);
int index = Arrays.binarySearch(anArray, 4);
System.out.println("Found at index " + index);
}
private static void merge() {
int[] anArray = new int[] {5, 2, 1, 4, 8};
int[] anotherArray = new int[] {10, 4, 9, 11, 2};
int[] resultArray = new int[anArray.length + anotherArray.length];
for (int i = 0; i < resultArray.length; i++) {
resultArray[i] = (i < anArray.length ? anArray[i] : anotherArray[i - anArray.length]);
}
for (int element : resultArray) {
System.out.println(element);
}
Arrays.setAll(resultArray, i -> (i < anArray.length ? anArray[i] : anotherArray[i - anArray.length]));
for (int element : resultArray) {
System.out.println(element);
}
}
}

View File

@@ -0,0 +1,20 @@
package com.baeldung.array;
public class Find2ndLargestInArray {
public static int find2ndLargestElement(int[] array) {
int maxElement = array[0];
int secondLargestElement = -1;
for (int index = 0; index < array.length; index++) {
if (maxElement <= array[index]) {
secondLargestElement = maxElement;
maxElement = array[index];
} else if (secondLargestElement < array[index]) {
secondLargestElement = array[index];
}
}
return secondLargestElement;
}
}

View File

@@ -0,0 +1,22 @@
package com.baeldung.array;
import java.util.Arrays;
public class FindElementInArray {
public static boolean findGivenElementInArrayWithoutUsingStream(int[] array, int element) {
boolean actualResult = false;
for (int index = 0; index < array.length; index++) {
if (element == array[index]) {
actualResult = true;
break;
}
}
return actualResult;
}
public static boolean findGivenElementInArrayUsingStream(int[] array, int element) {
return Arrays.stream(array).filter(x -> element == x).findFirst().isPresent();
}
}

View File

@@ -0,0 +1,49 @@
package com.baeldung.array;
import java.util.Arrays;
import java.util.Scanner;
public class JaggedArray {
int[][] shortHandFormInitialization() {
int[][] jaggedArr = { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } };
return jaggedArr;
}
int[][] declarationAndThenInitialization() {
int[][] jaggedArr = new int[3][];
jaggedArr[0] = new int[] { 1, 2 };
jaggedArr[1] = new int[] { 3, 4, 5 };
jaggedArr[2] = new int[] { 6, 7, 8, 9 };
return jaggedArr;
}
int[][] declarationAndThenInitializationUsingUserInputs() {
int[][] jaggedArr = new int[3][];
jaggedArr[0] = new int[2];
jaggedArr[1] = new int[3];
jaggedArr[2] = new int[4];
initializeElements(jaggedArr);
return jaggedArr;
}
void initializeElements(int[][] jaggedArr) {
Scanner sc = new Scanner(System.in);
for (int outer = 0; outer < jaggedArr.length; outer++) {
for (int inner = 0; inner < jaggedArr[outer].length; inner++) {
jaggedArr[outer][inner] = sc.nextInt();
}
}
}
void printElements(int[][] jaggedArr) {
for (int index = 0; index < jaggedArr.length; index++) {
System.out.println(Arrays.toString(jaggedArr[index]));
}
}
int[] getElementAtGivenIndex(int[][] jaggedArr, int index) {
return jaggedArr[index];
}
}

View File

@@ -0,0 +1,96 @@
package com.baeldung.array;
import org.openjdk.jmh.annotations.*;
import java.util.*;
import java.util.concurrent.TimeUnit;
@BenchmarkMode(Mode.AverageTime)
@Warmup(iterations = 5)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public class SearchArrayUnitTest {
@State(Scope.Benchmark)
public static class SearchData {
static int count = 1000;
static String[] strings = seedArray(1000);
}
@Benchmark
public void searchArrayLoop() {
for (int i = 0; i < SearchData.count; i++) {
searchLoop(SearchData.strings, "T");
}
}
@Benchmark
public void searchArrayAllocNewList() {
for (int i = 0; i < SearchData.count; i++) {
searchList(SearchData.strings, "T");
}
}
@Benchmark
public void searchArrayAllocNewSet() {
for (int i = 0; i < SearchData.count; i++) {
searchSet(SearchData.strings, "T");
}
}
@Benchmark
public void searchArrayReuseList() {
List<String> asList = Arrays.asList(SearchData.strings);
for (int i = 0; i < SearchData.count; i++) {
asList.contains("T");
}
}
@Benchmark
public void searchArrayReuseSet() {
Set<String> asSet = new HashSet<>(Arrays.asList(SearchData.strings));
for (int i = 0; i < SearchData.count; i++) {
asSet.contains("T");
}
}
@Benchmark
public void searchArrayBinarySearch() {
Arrays.sort(SearchData.strings);
for (int i = 0; i < SearchData.count; i++) {
Arrays.binarySearch(SearchData.strings, "T");
}
}
private boolean searchList(String[] strings, String searchString) {
return Arrays.asList(strings).contains(searchString);
}
private boolean searchSet(String[] strings, String searchString) {
Set<String> set = new HashSet<>(Arrays.asList(strings));
return set.contains(searchString);
}
private boolean searchLoop(String[] strings, String searchString) {
for (String s : strings) {
if (s.equals(searchString))
return true;
}
return false;
}
private static String[] seedArray(int length) {
String[] strings = new String[length];
Random random = new Random();
for (int i = 0; i < length; i++)
{
strings[i] = String.valueOf(random.nextInt());
}
return strings;
}
}

View File

@@ -0,0 +1,31 @@
package com.baeldung.array;
import java.util.Arrays;
public class SumAndAverageInArray {
public static int findSumWithoutUsingStream(int[] array) {
int sum = 0;
for (int value : array) {
sum += value;
}
return sum;
}
public static int findSumUsingStream(int[] array) {
return Arrays.stream(array).sum();
}
public static int findSumUsingStream(Integer[] array) {
return Arrays.stream(array).mapToInt(Integer::intValue).sum();
}
public static double findAverageWithoutUsingStream(int[] array) {
int sum = findSumWithoutUsingStream(array);
return (double) sum / array.length;
}
public static double findAverageUsingStream(int[] array) {
return Arrays.stream(array).average().orElse(Double.NaN);
}
}

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

@@ -0,0 +1,211 @@
package com.baeldung.array.operations;
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.Random;
import java.util.Set;
import java.util.function.Function;
import java.util.function.IntPredicate;
import java.util.function.Predicate;
import java.util.stream.Stream;
import org.apache.commons.lang3.ArrayUtils;
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);
}
}

View File

@@ -0,0 +1,61 @@
package com.baeldung.arraycopy.model;
public class Address implements Cloneable {
private String country;
private String state;
private String city;
private String street;
private String zipcode;
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getZipcode() {
return zipcode;
}
public void setZipcode(String zipcode) {
this.zipcode = zipcode;
}
@Override
protected Object clone() throws CloneNotSupportedException {
super.clone();
Address address = new Address();
address.setCity(this.city);
address.setCountry(this.country);
address.setState(this.state);
address.setStreet(this.street);
address.setZipcode(this.zipcode);
return address;
}
}

View File

@@ -0,0 +1,33 @@
package com.baeldung.arraycopy.model;
import java.io.Serializable;
public class Employee implements Serializable {
private static final long serialVersionUID = -2454619097207585825L;
private int id;
private String name;
public Employee() {
}
public Employee(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

View File

@@ -0,0 +1,44 @@
package com.baeldung.arrays;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.infra.Blackhole;
import java.util.Arrays;
public class ParallelPrefixBenchmark {
private static final int ARRAY_SIZE = 200_000_000;
@State(Scope.Benchmark)
public static class BigArray {
int[] data;
@Setup(Level.Iteration)
public void prepare() {
data = new int[ARRAY_SIZE];
for(int j = 0; j< ARRAY_SIZE; j++) {
data[j] = 1;
}
}
@TearDown(Level.Iteration)
public void destroy() {
data = null;
}
}
@Benchmark
public void largeArrayLoopSum(BigArray bigArray, Blackhole blackhole) {
for (int i = 0; i < ARRAY_SIZE - 1; i++) {
bigArray.data[i + 1] += bigArray.data[i];
}
blackhole.consume(bigArray.data);
}
@Benchmark
public void largeArrayParallelPrefixSum(BigArray bigArray, Blackhole blackhole) {
Arrays.parallelPrefix(bigArray.data, (left, right) -> left + right);
blackhole.consume(bigArray.data);
}
}

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,74 @@
package com.baeldung.array;
import static com.baeldung.array.ArrayInitializer.initializeArrayAtTimeOfDeclarationMethod1;
import static com.baeldung.array.ArrayInitializer.initializeArrayAtTimeOfDeclarationMethod2;
import static com.baeldung.array.ArrayInitializer.initializeArrayAtTimeOfDeclarationMethod3;
import static com.baeldung.array.ArrayInitializer.initializeArrayInLoop;
import static com.baeldung.array.ArrayInitializer.initializeArrayRangeUsingArraysFill;
import static com.baeldung.array.ArrayInitializer.initializeArrayUsingArraysCopy;
import static com.baeldung.array.ArrayInitializer.initializeArrayUsingArraysFill;
import static com.baeldung.array.ArrayInitializer.initializeArrayUsingArraysSetAll;
import static com.baeldung.array.ArrayInitializer.initializeArrayUsingArraysUtilClone;
import static com.baeldung.array.ArrayInitializer.initializeLargerArrayUsingArraysCopy;
import static com.baeldung.array.ArrayInitializer.initializeMultiDimensionalArrayInLoop;
import static org.junit.Assert.assertArrayEquals;
import org.junit.Test;
public class ArrayInitializerUnitTest {
@Test
public void whenInitializeArrayInLoop_thenCorrect() {
assertArrayEquals(new int[] { 2, 3, 4, 5, 6 }, initializeArrayInLoop());
}
@Test
public void whenInitializeMultiDimensionalArrayInLoop_thenCorrect() {
assertArrayEquals(new int[][] { { 1, 2, 3, 4, 5 }, { 1, 2, 3, 4, 5 } }, initializeMultiDimensionalArrayInLoop());
}
@Test
public void whenInitializeArrayAtTimeOfDeclarationMethod1_thenCorrect() {
assertArrayEquals(new String[] { "Toyota", "Mercedes", "BMW", "Volkswagen", "Skoda" }, initializeArrayAtTimeOfDeclarationMethod1());
}
@Test
public void whenInitializeArrayAtTimeOfDeclarationMethod2_thenCorrect() {
assertArrayEquals(new int[] { 1, 2, 3, 4, 5 }, initializeArrayAtTimeOfDeclarationMethod2());
}
@Test
public void whenInitializeArrayAtTimeOfDeclarationMethod3_thenCorrect() {
assertArrayEquals(new int[] { 1, 2, 3, 4, 5 }, initializeArrayAtTimeOfDeclarationMethod3());
}
@Test
public void whenInitializeArrayUsingArraysFill_thenCorrect() {
assertArrayEquals(new long[] { 30, 30, 30, 30, 30 }, initializeArrayUsingArraysFill());
}
@Test
public void whenInitializeArrayRangeUsingArraysFill_thenCorrect() {
assertArrayEquals(new int[] { -50, -50, -50, 0, 0 }, initializeArrayRangeUsingArraysFill());
}
@Test
public void whenInitializeArrayRangeUsingArraysCopy_thenCorrect() {
assertArrayEquals(new int[] { 1, 2, 3, 4, 5 }, initializeArrayUsingArraysCopy());
}
@Test
public void whenInitializeLargerArrayRangeUsingArraysCopy_thenCorrect() {
assertArrayEquals(new int[] { 1, 2, 3, 4, 5, 0 }, initializeLargerArrayUsingArraysCopy());
}
@Test
public void whenInitializeLargerArrayRangeUsingArraysSetAll_thenCorrect() {
assertArrayEquals(new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, initializeArrayUsingArraysSetAll());
}
@Test
public void whenInitializeArrayUsingArraysUtilClone_thenCorrect() {
assertArrayEquals(new char[] { 'a', 'b', 'c' }, initializeArrayUsingArraysUtilClone());
}
}

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));
}
}

View File

@@ -0,0 +1,16 @@
package com.baeldung.array;
import org.junit.Assert;
import org.junit.Test;
public class Find2ndLargestInArrayUnitTest {
@Test
public void givenAnIntArray_thenFind2ndLargestElement() {
int[] array = { 1, 3, 24, 16, 87, 20 };
int expected2ndLargest = 24;
int actualSecondLargestElement = Find2ndLargestInArray.find2ndLargestElement(array);
Assert.assertEquals(expected2ndLargest, actualSecondLargestElement);
}
}

View File

@@ -0,0 +1,35 @@
package com.baeldung.array;
import org.junit.Assert;
import org.junit.Test;
public class FindElementInArrayUnitTest {
@Test
public void givenAnIntArray_whenNotUsingStream_thenFindAnElement() {
int[] array = { 1, 3, 4, 8, 19, 20 };
int element = 19;
boolean expectedResult = true;
boolean actualResult = FindElementInArray.findGivenElementInArrayWithoutUsingStream(array, element);
Assert.assertEquals(expectedResult, actualResult);
element = 78;
expectedResult = false;
actualResult = FindElementInArray.findGivenElementInArrayWithoutUsingStream(array, element);
Assert.assertEquals(expectedResult, actualResult);
}
@Test
public void givenAnIntArray_whenUsingStream_thenFindAnElement() {
int[] array = { 15, 16, 12, 18 };
int element = 16;
boolean expectedResult = true;
boolean actualResult = FindElementInArray.findGivenElementInArrayUsingStream(array, element);
Assert.assertEquals(expectedResult, actualResult);
element = 20;
expectedResult = false;
actualResult = FindElementInArray.findGivenElementInArrayUsingStream(array, element);
Assert.assertEquals(expectedResult, actualResult);
}
}

View File

@@ -0,0 +1,53 @@
package com.baeldung.array;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.PrintStream;
import org.junit.Test;
public class JaggedArrayUnitTest {
private JaggedArray obj = new JaggedArray();
@Test
public void whenInitializedUsingShortHandForm_thenCorrect() {
assertArrayEquals(new int[][] { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }, obj.shortHandFormInitialization());
}
@Test
public void whenInitializedWithDeclarationAndThenInitalization_thenCorrect() {
assertArrayEquals(new int[][] { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }, obj.declarationAndThenInitialization());
}
@Test
public void whenInitializedWithDeclarationAndThenInitalizationUsingUserInputs_thenCorrect() {
InputStream is = new ByteArrayInputStream("1 2 3 4 5 6 7 8 9".getBytes());
System.setIn(is);
assertArrayEquals(new int[][] { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }, obj.declarationAndThenInitializationUsingUserInputs());
System.setIn(System.in);
}
@Test
public void givenJaggedArrayAndAnIndex_thenReturnArrayAtGivenIndex() {
int[][] jaggedArr = { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } };
assertArrayEquals(new int[] { 1, 2 }, obj.getElementAtGivenIndex(jaggedArr, 0));
assertArrayEquals(new int[] { 3, 4, 5 }, obj.getElementAtGivenIndex(jaggedArr, 1));
assertArrayEquals(new int[] { 6, 7, 8, 9 }, obj.getElementAtGivenIndex(jaggedArr, 2));
}
@Test
public void givenJaggedArray_whenUsingArraysAPI_thenVerifyPrintedElements() {
int[][] jaggedArr = { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } };
ByteArrayOutputStream outContent = new ByteArrayOutputStream();
System.setOut(new PrintStream(outContent));
obj.printElements(jaggedArr);
assertEquals("[1, 2][3, 4, 5][6, 7, 8, 9]", outContent.toString().replace("\r", "").replace("\n", ""));
System.setOut(System.out);
}
}

View File

@@ -0,0 +1,59 @@
package com.baeldung.array;
import org.junit.Assert;
import org.junit.Test;
public class SumAndAverageInArrayUnitTest {
@Test
public void givenAnIntArray_whenNotUsingStream_thenFindSum() {
int[] array = { 1, 3, 4, 8, 19, 20 };
int expectedSumOfArray = 55;
int actualSumOfArray = SumAndAverageInArray.findSumWithoutUsingStream(array);
Assert.assertEquals(expectedSumOfArray, actualSumOfArray);
}
@Test
public void givenAnIntArray_whenUsingStream_thenFindSum() {
int[] array = { 1, 3, 4, 8, 19, 20 };
int expectedSumOfArray = 55;
int actualSumOfArray = SumAndAverageInArray.findSumUsingStream(array);
Assert.assertEquals(expectedSumOfArray, actualSumOfArray);
}
@Test
public void givenAnBoxedIntegerArray_whenUsingStream_thenFindSum() {
Integer[] array = new Integer[]{1, 3, 4, 8, 19, 20};
int expectedSumOfArray = 55;
int actualSumOfArray = SumAndAverageInArray.findSumUsingStream(array);
Assert.assertEquals(expectedSumOfArray, actualSumOfArray);
}
@Test
public void givenAnIntArray_whenNotUsingStream_thenFindAverage() {
int[] array = { 1, 3, 4, 8, 19, 20 };
double expectedAvgOfArray = 9.17;
double actualAvgOfArray = SumAndAverageInArray.findAverageWithoutUsingStream(array);
Assert.assertEquals(expectedAvgOfArray, actualAvgOfArray, 0.0034);
}
@Test
public void givenAnIntArray_whenUsingStream_thenFindAverage() {
int[] array = { 1, 3, 4, 8, 19, 20 };
double expectedAvgOfArray = 9.17;
double actualAvgOfArray = SumAndAverageInArray.findAverageUsingStream(array);
Assert.assertEquals(expectedAvgOfArray, actualAvgOfArray, 0.0034);
}
@Test
public void givenAnEmptyIntArray_whenUsingStream_thenFindAverage() {
int[] array = {};
double expectedAvgOfArray = Double.NaN;
double actualAvgOfArray = SumAndAverageInArray.findAverageUsingStream(array);
Assert.assertEquals(expectedAvgOfArray, actualAvgOfArray, 0.00);
}
}

View File

@@ -0,0 +1,46 @@
package com.baeldung.array.conversions;
import static com.baeldung.array.conversions.FloatToByteArray.byteArrayToFloat;
import static com.baeldung.array.conversions.FloatToByteArray.byteArrayToFloatWithByteBuffer;
import static com.baeldung.array.conversions.FloatToByteArray.floatToByteArray;
import static com.baeldung.array.conversions.FloatToByteArray.floatToByteArrayWithByteBuffer;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
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

@@ -0,0 +1,365 @@
package com.baeldung.array.operations;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Arrays;
import org.assertj.core.api.Condition;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
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);
}
}

View File

@@ -0,0 +1,66 @@
package com.baeldung.array.operations;
import org.junit.jupiter.api.Test;
import static com.baeldung.array.operations.ArrayOperations.intersectionMultiSet;
import static com.baeldung.array.operations.ArrayOperations.intersectionSet;
import static com.baeldung.array.operations.ArrayOperations.intersectionSimple;
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,170 @@
package com.baeldung.arraycopy;
import com.baeldung.arraycopy.model.Address;
import com.baeldung.arraycopy.model.Employee;
import org.apache.commons.lang3.SerializationUtils;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import java.util.Arrays;
import static org.junit.Assert.assertTrue;
public class ArrayCopyUtilUnitTest {
private static Employee[] employees;
private static final int MAX = 2;
@BeforeClass
public static void setup(){
createEmployeesArray();
}
private static void createEmployeesArray() {
employees = new Employee[MAX];
Employee employee;
for(int i = 0; i < MAX; i++) {
employee = new Employee();
employee.setName("Emp"+i);
employee.setId(i);
employees[i] = employee;
}
}
@Test
public void givenArrayOfPrimitiveType_whenCopiedViaSystemsArrayCopy_thenSuccessful(){
int[] array = {23, 43, 55};
int[] copiedArray = new int[3];
System.arraycopy(array, 0, copiedArray, 0, 3);
Assert.assertArrayEquals(copiedArray, array);
}
@Test
public void givenArrayOfPrimitiveType_whenCopiedSubSequenceViaSystemsArrayCopy_thenSuccessful(){
int[] array = {23, 43, 55, 12, 65, 88, 92};
int[] copiedArray = new int[3];
System.arraycopy(array, 2, copiedArray, 0, 3);
assertTrue(3 == copiedArray.length);
assertTrue(copiedArray[0] == array[2]);
assertTrue(copiedArray[1] == array[3]);
assertTrue(copiedArray[2] == array[4]);
}
@Test
public void givenArrayOfPrimitiveType_whenCopiedSubSequenceViaArraysCopyOfRange_thenSuccessful(){
int[] array = {23, 43, 55, 12, 65, 88, 92};
int[] copiedArray = Arrays.copyOfRange(array, 1, 4);
assertTrue(3 == copiedArray.length);
assertTrue(copiedArray[0] == array[1]);
assertTrue(copiedArray[1] == array[2]);
assertTrue(copiedArray[2] == array[3]);
}
@Test
public void givenArrayOfPrimitiveType_whenCopiedViaArraysCopyOf_thenValueChangeIsSuccessful(){
int[] array = {23, 43, 55, 12};
int newLength = array.length;
int[] copiedArray = Arrays.copyOf(array, newLength);
Assert.assertArrayEquals(copiedArray, array);
array[0] = 9;
assertTrue(copiedArray[0] != array[0]);
copiedArray[1] = 12;
assertTrue(copiedArray[1] != array[1]);
}
@Test
public void givenArrayOfNonPrimitiveType_whenCopiedViaArraysCopyOf_thenDoShallowCopy(){
Employee[] copiedArray = Arrays.copyOf(employees, employees.length);
Assert.assertArrayEquals(copiedArray, employees);
employees[0].setName(employees[0].getName()+"_Changed");
//change in employees' element caused change in the copied array
assertTrue(copiedArray[0].getName().equals(employees[0].getName()));
}
@Test
public void givenArrayOfPrimitiveType_whenCopiedViaArrayClone_thenValueChangeIsSuccessful(){
int[] array = {23, 43, 55, 12};
int[] copiedArray = array.clone();
Assert.assertArrayEquals(copiedArray, array);
array[0] = 9;
assertTrue(copiedArray[0] != array[0]);
copiedArray[1] = 12;
assertTrue(copiedArray[1] != array[1]);
}
@Test
public void givenArraysOfNonPrimitiveType_whenCopiedViaArrayClone_thenDoShallowCopy(){
Employee[] copiedArray = employees.clone();
Assert.assertArrayEquals(copiedArray, employees);;
employees[0].setName(employees[0].getName()+"_Changed");
//change in employees' element changed the copied array
assertTrue(copiedArray[0].getName().equals(employees[0].getName()));
}
@Test
public void givenArraysOfCloneableNonPrimitiveType_whenCopiedViaArrayClone_thenDoShallowCopy(){
Address[] addresses = createAddressArray();
Address[] copiedArray = addresses.clone();
addresses[0].setCity(addresses[0].getCity()+"_Changed");
Assert.assertArrayEquals(copiedArray, addresses);
}
@Test
public void givenArraysOfSerializableNonPrimitiveType_whenCopiedViaSerializationUtils_thenDoDeepCopy(){
Employee[] copiedArray = SerializationUtils.clone(employees);
employees[0].setName(employees[0].getName()+"_Changed");
//change in employees' element didn't change in the copied array
Assert.assertFalse(
copiedArray[0].getName().equals(employees[0].getName()));
}
@Test
public void givenArraysOfNonPrimitiveType_whenCopiedViaStream_thenDoShallowCopy(){
Employee[] copiedArray = Arrays.stream(employees).toArray(Employee[]::new);
Assert.assertArrayEquals(copiedArray, employees);
employees[0].setName(employees[0].getName()+"_Changed");
//change in employees' element didn't change in the copied array
assertTrue(copiedArray[0].getName().equals(employees[0].getName()));
}
@Test
public void givenArraysOfPrimitiveType_whenCopiedViaStream_thenSuccessful(){
String[] strArray = {"orange", "red", "green'"};
String[] copiedArray = Arrays.stream(strArray).toArray(String[]::new);
Assert.assertArrayEquals(copiedArray, strArray);
}
private Address[] createAddressArray(){
Address[] addresses = new Address[1];
addresses[0] = createAddress();
return addresses;
}
private Address createAddress() {
Address address = new Address();
address.setCountry("USA");
address.setState("CA");
address.setCity("San Francisco");
address.setStreet("Street 1");
address.setZipcode("59999");
return address;
}
}

View File

@@ -0,0 +1,204 @@
package com.baeldung.arrays;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.stream.Stream;
public class ArraysUnitTest {
private String[] intro;
@Rule
public final ExpectedException exception = ExpectedException.none();
@Before
public void setup() {
intro = new String[] { "once", "upon", "a", "time" };
}
@Test
public void whenCopyOfRange_thenAbridgedArray() {
String[] abridgement = Arrays.copyOfRange(intro, 0, 3);
assertArrayEquals(new String[] { "once", "upon", "a" }, abridgement);
assertFalse(Arrays.equals(intro, abridgement));
}
@Test
public void whenCopyOf_thenNullElement() {
String[] revised = Arrays.copyOf(intro, 3);
String[] expanded = Arrays.copyOf(intro, 5);
assertArrayEquals(Arrays.copyOfRange(intro, 0, 3), revised);
assertNull(expanded[4]);
}
@Test
public void whenFill_thenAllMatch() {
String[] stutter = new String[3];
Arrays.fill(stutter, "once");
assertTrue(Stream.of(stutter).allMatch(el -> "once".equals(el)));
}
@Test
public void whenEqualsContent_thenMatch() {
assertTrue(Arrays.equals(new String[] { "once", "upon", "a", "time" }, intro));
assertFalse(Arrays.equals(new String[] { "once", "upon", "a", null }, intro));
}
@Test
public void whenNestedArrays_thenDeepEqualsPass() {
String[] end = { "the", "end" };
Object[] story = new Object[] { intro, new String[] { "chapter one", "chapter two" }, end };
Object[] copy = new Object[] { intro, new String[] { "chapter one", "chapter two" }, end };
assertTrue(Arrays.deepEquals(story, copy));
assertFalse(Arrays.equals(story, copy));
}
@Test
public void whenSort_thenArraySorted() {
String[] sorted = Arrays.copyOf(intro, 4);
Arrays.sort(sorted);
assertArrayEquals(new String[] { "a", "once", "time", "upon" }, sorted);
}
@Test
public void whenBinarySearch_thenFindElements() {
String[] sorted = Arrays.copyOf(intro, 4);
Arrays.sort(sorted);
int exact = Arrays.binarySearch(sorted, "time");
int caseInsensitive = Arrays.binarySearch(sorted, "TiMe", String::compareToIgnoreCase);
assertEquals("time", sorted[exact]);
assertEquals(2, exact);
assertEquals(exact, caseInsensitive);
}
@Test
public void whenNullElement_thenArraysHashCodeNotEqual() {
int beforeChange = Arrays.hashCode(intro);
int before = intro.hashCode();
intro[3] = null;
int after = intro.hashCode();
int afterChange = Arrays.hashCode(intro);
assertNotEquals(beforeChange, afterChange);
assertEquals(before, after);
}
@Test
public void whenNestedArrayNullElement_thenEqualsFailDeepHashPass() {
Object[] looping = new Object[] { intro, intro };
int deepHashBefore = Arrays.deepHashCode(looping);
int hashBefore = Arrays.hashCode(looping);
intro[3] = null;
int hashAfter = Arrays.hashCode(looping);
int deepHashAfter = Arrays.deepHashCode(looping);
assertEquals(hashAfter, hashBefore);
assertNotEquals(deepHashAfter, deepHashBefore);
}
@Test
public void whenStreamBadIndex_thenException() {
assertEquals(Arrays.stream(intro).count(), 4);
exception.expect(ArrayIndexOutOfBoundsException.class);
Arrays.stream(intro, 2, 1).count();
}
@Test
public void whenSetAllToUpper_thenAppliedToAllElements() {
String[] longAgo = new String[4];
Arrays.setAll(longAgo, i -> intro[i].toUpperCase());
assertArrayEquals(longAgo, new String[] { "ONCE", "UPON", "A", "TIME" });
}
@Test
public void whenToString_thenFormattedArrayString() {
assertEquals("[once, upon, a, time]", Arrays.toString(intro));
}
@Test
public void whenNestedArrayDeepString_thenFormattedArraysString() {
String[] end = { "the", "end" };
Object[] story = new Object[] { intro, new String[] { "chapter one", "chapter two" }, end };
assertEquals("[[once, upon, a, time], [chapter one, chapter two], [the, end]]", Arrays.deepToString(story));
}
@Test
public void whenAsList_thenImmutableArray() {
List<String> rets = Arrays.asList(intro);
assertTrue(rets.contains("upon"));
assertTrue(rets.contains("time"));
assertEquals(rets.size(), 4);
exception.expect(UnsupportedOperationException.class);
rets.add("the");
}
@Test
public void givenIntArray_whenPrefixAdd_thenAllAccumulated() {
int[] arri = new int[] { 1, 2, 3, 4};
Arrays.parallelPrefix(arri, (left, right) -> left + right);
assertThat(arri, is(new int[] { 1, 3, 6, 10}));
}
@Test
public void givenStringArray_whenPrefixConcat_thenAllMerged() {
String[] arrs = new String[] { "1", "2", "3" };
Arrays.parallelPrefix(arrs, (left, right) -> left + right);
assertThat(arrs, is(new String[] { "1", "12", "123" }));
}
@Test
public void whenPrefixAddWithRange_thenRangeAdded() {
int[] arri = new int[] { 1, 2, 3, 4, 5 };
Arrays.parallelPrefix(arri, 1, 4, (left, right) -> left + right);
assertThat(arri, is(new int[] { 1, 2, 5, 9, 5 }));
}
@Test
public void whenPrefixNonAssociative_thenError() {
boolean consistent = true;
Random r = new Random();
for (int k = 0; k < 100_000; k++) {
int[] arrA = r.ints(100, 1, 5).toArray();
int[] arrB = Arrays.copyOf(arrA, arrA.length);
Arrays.parallelPrefix(arrA, this::nonassociativeFunc);
for (int i = 1; i < arrB.length; i++) {
arrB[i] = nonassociativeFunc(arrB[i - 1], arrB[i]);
}
consistent = Arrays.equals(arrA, arrB);
if(!consistent) break;
}
assertFalse(consistent);
}
/**
* non-associative int binary operator
*/
private int nonassociativeFunc(int left, int right) {
return left + right*left;
}
}

View File

@@ -0,0 +1,90 @@
package com.baeldung.sort;
import com.baeldung.arraycopy.model.Employee;
import org.junit.Before;
import org.junit.Test;
import java.util.Arrays;
import java.util.Comparator;
import java.util.stream.IntStream;
import static org.junit.Assert.assertArrayEquals;
public class ArraySortUnitTest {
private Employee[] employees;
private int[] numbers;
private String[] strings;
private Employee john = new Employee(6, "John");
private Employee mary = new Employee(3, "Mary");
private Employee david = new Employee(4, "David");
@Before
public void setup() {
createEmployeesArray();
createNumbersArray();
createStringArray();
}
private void createEmployeesArray() {
employees = new Employee[]{john, mary, david};
}
private void createNumbersArray() {
numbers = new int[]{-8, 7, 5, 9, 10, -2, 3};
}
private void createStringArray() {
strings = new String[]{"learning", "java", "with", "baeldung"};
}
@Test
public void givenIntArray_whenSortingAscending_thenCorrectlySorted() {
Arrays.sort(numbers);
assertArrayEquals(new int[]{-8, -2, 3, 5, 7, 9, 10}, numbers);
}
@Test
public void givenIntArray_whenSortingDescending_thenCorrectlySorted() {
numbers = IntStream.of(numbers).boxed().sorted(Comparator.reverseOrder()).mapToInt(i -> i).toArray();
assertArrayEquals(new int[]{10, 9, 7, 5, 3, -2, -8}, numbers);
}
@Test
public void givenStringArray_whenSortingAscending_thenCorrectlySorted() {
Arrays.sort(strings);
assertArrayEquals(new String[]{"baeldung", "java", "learning", "with"}, strings);
}
@Test
public void givenStringArray_whenSortingDescending_thenCorrectlySorted() {
Arrays.sort(strings, Comparator.reverseOrder());
assertArrayEquals(new String[]{"with", "learning", "java", "baeldung"}, strings);
}
@Test
public void givenObjectArray_whenSortingAscending_thenCorrectlySorted() {
Arrays.sort(employees, Comparator.comparing(Employee::getName));
assertArrayEquals(new Employee[]{david, john, mary}, employees);
}
@Test
public void givenObjectArray_whenSortingDescending_thenCorrectlySorted() {
Arrays.sort(employees, Comparator.comparing(Employee::getName).reversed());
assertArrayEquals(new Employee[]{mary, john, david}, employees);
}
@Test
public void givenObjectArray_whenSortingMultipleAttributesAscending_thenCorrectlySorted() {
Arrays.sort(employees, Comparator.comparing(Employee::getName).thenComparing(Employee::getId));
assertArrayEquals(new Employee[]{david, john, mary}, employees);
}
}