Merge branch 'master' into master

This commit is contained in:
Loredana Crusoveanu
2024-04-27 14:05:55 +03:00
committed by GitHub
162 changed files with 4745 additions and 504 deletions
@@ -13,4 +13,12 @@
<version>0.0.1-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.14.0</version>
</dependency>
</dependencies>
</project>
@@ -0,0 +1,130 @@
package com.baeldung.array.flatarray;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
class FlatArrayUnitTest {
@ParameterizedTest
@MethodSource("arrayProvider")
void giveTwoDimensionalArray_whenFlatWithStream_thenGetCorrectResult(int[][] initialArray,
int[] expected) {
int[] actual = Arrays.stream(initialArray).flatMapToInt(Arrays::stream).toArray();
assertThat(actual).containsExactly(expected);
}
@ParameterizedTest
@MethodSource("arrayProvider")
void giveTwoDimensionalArray_whenFlatWithForLoopAndAdditionalList_thenGetCorrectResult(int[][] initialArray,
int[] intArray) {
List<Integer> expected = Arrays.stream(intArray).boxed().collect(Collectors.toList());
List<Integer> actual = new ArrayList<>();
for (int[] numbers : initialArray) {
for (int number : numbers) {
actual.add(number);
}
}
assertThat(actual).isEqualTo(expected);
}
@ParameterizedTest
@MethodSource("arrayProvider")
void giveTwoDimensionalArray_whenFlatWithForLoopAndLists_thenGetCorrectResult(int[][] initialArray,
int[] intArray) {
List<Integer> expected = Arrays.stream(intArray).boxed().collect(Collectors.toList());
List<Integer> actual = new ArrayList<>();
for (int[] numbers : initialArray) {
List<Integer> listOfNumbers = Arrays.stream(numbers).boxed().collect(Collectors.toList());
actual.addAll(listOfNumbers);
}
assertThat(actual).isEqualTo(expected);
}
@ParameterizedTest
@MethodSource("arrayProvider")
void giveTwoDimensionalArray_whenFlatWithArrayCopy_thenGetCorrectResult(int[][] initialArray,
int[] expected) {
int[] actual = new int[]{};
int position = 0;
for (int[] numbers : initialArray) {
if (actual.length < position + numbers.length) {
int[] newArray = new int[actual.length + numbers.length];
System.arraycopy(actual, 0, newArray, 0, actual.length);
actual = newArray;
}
System.arraycopy(numbers, 0, actual, position, numbers.length);
position += numbers.length;
}
assertThat(actual).isEqualTo(expected);
}
@ParameterizedTest
@MethodSource("arrayProvider")
void giveTwoDimensionalArray_whenFlatWithArrayCopyAndTotalNumberOfElements_thenGetCorrectResult(int[][] initialArray,
int[] expected) {
int totalNumberOfElements = 0;
for (int[] numbers : initialArray) {
totalNumberOfElements += numbers.length;
}
int[] actual = new int[totalNumberOfElements];
int position = 0;
for (int[] numbers : initialArray) {
System.arraycopy(numbers, 0, actual, position, numbers.length);
position += numbers.length;
}
assertThat(actual).isEqualTo(expected);
}
@ParameterizedTest
@MethodSource("arrayProvider")
void giveTwoDimensionalArray_whenFlatWithForLoopAndTotalNumberOfElements_thenGetCorrectResult(int[][] initialArray,
int[] expected) {
int totalNumberOfElements = 0;
for (int[] numbers : initialArray) {
totalNumberOfElements += numbers.length;
}
int[] actual = new int[totalNumberOfElements];
int position = 0;
for (int[] numbers : initialArray) {
for (int number : numbers) {
actual[position] = number;
++position;
}
}
assertThat(actual).isEqualTo(expected);
}
static Stream<Arguments> arrayProvider() {
return Stream.of(
Arguments.of(
new int[][]{
{805, 902, 259, 162, 775},
{278, 216, 0, 72, 663},
{185, 390, 537, 909, 918},
{150, 782, 282, 482, 401},
{244, 685, 643, 364, 307},
{483, 939, 750, 190, 424},
{44, 160, 290, 963, 881}
},
new int[]{
805, 902, 259, 162, 775,
278, 216, 0, 72, 663,
185, 390, 537, 909, 918,
150, 782, 282, 482, 401,
244, 685, 643, 364, 307,
483, 939, 750, 190, 424,
44, 160, 290, 963, 881
}
)
);
}
}
@@ -0,0 +1,132 @@
package com.baeldung.array.smallestindex;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import org.apache.commons.lang3.ArrayUtils;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
class SmallestElementIndexUnitTest {
@ParameterizedTest
@MethodSource("primitiveProvider")
void givenArray_whenUsingForLoop_thenGetCorrectResult(int[] array, int expectedIndex) {
int minValue = Integer.MAX_VALUE;
int minIndex = -1;
for (int i = 0; i < array.length; i++) {
if (array[i] < minValue) {
minValue = array[i];
minIndex = i;
}
}
assertThat(minIndex).isEqualTo(expectedIndex);
}
@ParameterizedTest
@MethodSource("primitiveProvider")
void givenArray_whenUsingForLoopAndLookForIndex_thenGetCorrectResult(int[] array, int expectedIndex) {
int minValue = Integer.MAX_VALUE;
for (int number : array) {
if (number < minValue) {
minValue = number;
}
}
int minIndex = -1;
for (int i = 0; i < array.length; i++) {
if (array[i] == minValue) {
minIndex = i;
break;
}
}
assertThat(minIndex).isEqualTo(expectedIndex);
}
@ParameterizedTest
@MethodSource("primitiveProvider")
void givenArray_whenUsingIntStreamAndLookForIndex_thenGetCorrectResult(int[] array, int expectedIndex) {
int minValue = Arrays.stream(array).min().orElse(Integer.MAX_VALUE);
int minIndex = -1;
for (int i = 0; i < array.length; i++) {
if (array[i] == minValue) {
minIndex = i;
break;
}
}
assertThat(minIndex).isEqualTo(expectedIndex);
}
@ParameterizedTest
@MethodSource("primitiveProvider")
void givenArray_whenUsingIntStreamAndLookForIndexWithIntStream_thenGetCorrectResult(int[] array, int expectedIndex) {
int minValue = Arrays.stream(array).min().orElse(Integer.MAX_VALUE);
int minIndex = IntStream.range(0, array.length)
.filter(index -> array[index] == minValue)
.findFirst().orElse(-1);
assertThat(minIndex).isEqualTo(expectedIndex);
}
@ParameterizedTest
@MethodSource("primitiveProvider")
void givenArray_whenUsingIntStreamAndLookForIndexWithArrayUtils_thenGetCorrectResult(int[] array, int expectedIndex) {
int minValue = Arrays.stream(array).min().orElse(Integer.MAX_VALUE);
int minIndex = ArrayUtils.indexOf(array, minValue);
assertThat(minIndex).isEqualTo(expectedIndex);
}
@ParameterizedTest
@MethodSource("referenceTypesProvider")
void givenArray_whenUsingReduce_thenGetCorrectResult(Integer[] array, int expectedIndex) {
int minValue = Arrays.stream(array).reduce(Integer.MAX_VALUE, Integer::min);
int minIndex = ArrayUtils.indexOf(array, minValue);
assertThat(minIndex).isEqualTo(expectedIndex);
}
@ParameterizedTest
@MethodSource("referenceTypesProvider")
void givenArray_whenUsingReduceAndList_thenGetCorrectResult(Integer[] array, int expectedIndex) {
List<Integer> list = Arrays.asList(array);
int minValue = list.stream().reduce(Integer.MAX_VALUE, Integer::min);
int index = list.indexOf(minValue);
assertThat(index).isEqualTo(expectedIndex);
}
@ParameterizedTest
@MethodSource("primitiveProvider")
void givenArray_whenUsingReduceWithRange_thenGetCorrectResult(int[] array, int expectedIndex) {
int index = IntStream.range(0, array.length)
.reduce((a, b) -> array[a] <= array[b] ? a : b)
.orElse(-1);
assertThat(index).isEqualTo(expectedIndex);
}
@ParameterizedTest
@MethodSource("primitiveProvider")
void givenArray_whenUsingPrimitiveStreams_thenGetCorrectResult(int[] array, int expectedIndex) {
List<Integer> list = Arrays.stream(array).boxed().collect(Collectors.toList());
int minValue = Arrays.stream(array).min().orElse(Integer.MAX_VALUE);
int index = list.indexOf(minValue);
assertThat(index).isEqualTo(expectedIndex);
}
static Stream<Arguments> primitiveProvider() {
return Stream.of(
Arguments.of(new int[]{585, 190, 201, 82, 332}, 3),
Arguments.of(new int[]{1, 1, 1}, 0),
Arguments.of(new int[]{}, -1)
);
}
static Stream<Arguments> referenceTypesProvider() {
return Stream.of(
Arguments.of(new Integer[]{585, 190, 201, 82, 332}, 3),
Arguments.of(new Integer[]{1, 1, 1}, 0),
Arguments.of(new Integer[]{}, -1)
);
}
}
@@ -7,10 +7,8 @@
- [Creating Custom Iterator in Java](https://www.baeldung.com/java-creating-custom-iterator)
- [Difference Between Arrays.sort() and Collections.sort()](https://www.baeldung.com/java-arrays-collections-sort-methods)
- [Skipping the First Iteration in Java](https://www.baeldung.com/java-skip-first-iteration)
- [Remove Elements From a Queue Using Loop](https://www.baeldung.com/java-remove-elements-queue)
- [Intro to Vector Class in Java](https://www.baeldung.com/java-vector-guide)
- [Time Complexity of Java Collections Sort in Java](https://www.baeldung.com/java-time-complexity-collections-sort)
- [Check if List Contains at Least One Enum](https://www.baeldung.com/java-list-check-enum-presence)
- [Comparison of for Loops and Iterators](https://www.baeldung.com/java-for-loops-vs-iterators)
- [PriorityQueue iterator() Method in Java](https://www.baeldung.com/java-priorityqueue-iterator)
- [Immutable vs Unmodifiable Collection in Java](https://www.baeldung.com/java-collection-immutable-unmodifiable-differences)
@@ -5,4 +5,7 @@
### Relevant Articles:
- [Iterator vs forEach() in Java](https://www.baeldung.com/java-iterator-vs-foreach)
- [Adding Elements to a Collection During Iteration](https://www.baeldung.com/java-add-elements-collection)
- [Remove Elements From a Queue Using Loop](https://www.baeldung.com/java-remove-elements-queue)
- [Check if List Contains at Least One Enum](https://www.baeldung.com/java-list-check-enum-presence)
- More articles: [[<-- prev]](/core-java-modules/core-java-collections-5)
@@ -1,57 +1,57 @@
package com.baeldung.checkiflistcontainsenum;
import org.junit.Assert;
import org.junit.Test;
import java.util.*;
public class CheckIfListContainsEnumUnitTest {
private final List<Map<String, Object>> data = new ArrayList<>();
public CheckIfListContainsEnumUnitTest() {
Map<String, Object> map = new HashMap<>();
map.put("Name", "John");
map.put("Age", 25);
map.put("Position", Position.DEVELOPER);
data.add(map);
}
@Test
public void givenDataList_whenUsingLoop_thenCheckIfListContainsEnum() {
boolean containsEnumValue = false;
for (Map<String, Object> entry : data) {
Object positionValue = entry.get("Position");
if (Arrays.asList(Position.values()).contains(positionValue)) {
containsEnumValue = true;
break;
}
}
Assert.assertTrue(containsEnumValue);
}
@Test
public void givenDataList_whenUsingStream_thenCheckIfListContainsEnum() {
boolean containsEnumValue = data.stream()
.map(entry -> entry.get("Position"))
.anyMatch(position -> Arrays.asList(Position.values()).contains(position));
Assert.assertTrue(containsEnumValue);
}
@Test
public void givenDataList_whenUsingDisjointMethod_thenCheckIfListContainsEnum() {
List<Position> positionValues = data.stream()
.map(entry -> (Position) entry.get("Position"))
.toList();
boolean containsEnumValue = !Collections.disjoint(Arrays.asList(Position.values()), positionValues);
Assert.assertTrue(containsEnumValue);
}
public enum Position {
DEVELOPER, MANAGER, ANALYST
}
}
package com.baeldung.checkiflistcontainsenum;
import org.junit.Assert;
import org.junit.Test;
import java.util.*;
public class CheckIfListContainsEnumUnitTest {
private final List<Map<String, Object>> data = new ArrayList<>();
public CheckIfListContainsEnumUnitTest() {
Map<String, Object> map = new HashMap<>();
map.put("Name", "John");
map.put("Age", 25);
map.put("Position", Position.DEVELOPER);
data.add(map);
}
@Test
public void givenDataList_whenUsingLoop_thenCheckIfListContainsEnum() {
boolean containsEnumValue = false;
for (Map<String, Object> entry : data) {
Object positionValue = entry.get("Position");
if (Arrays.asList(Position.values()).contains(positionValue)) {
containsEnumValue = true;
break;
}
}
Assert.assertTrue(containsEnumValue);
}
@Test
public void givenDataList_whenUsingStream_thenCheckIfListContainsEnum() {
boolean containsEnumValue = data.stream()
.map(entry -> entry.get("Position"))
.anyMatch(position -> Arrays.asList(Position.values()).contains(position));
Assert.assertTrue(containsEnumValue);
}
@Test
public void givenDataList_whenUsingDisjointMethod_thenCheckIfListContainsEnum() {
List<Position> positionValues = data.stream()
.map(entry -> (Position) entry.get("Position"))
.toList();
boolean containsEnumValue = !Collections.disjoint(Arrays.asList(Position.values()), positionValues);
Assert.assertTrue(containsEnumValue);
}
public enum Position {
DEVELOPER, MANAGER, ANALYST
}
}
@@ -1,60 +1,60 @@
package com.baeldung.removequeueelements;
import org.junit.Test;
import java.util.LinkedList;
import java.util.Queue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class RemoveQueueElementsUnitTest {
@Test
public void givenQueueWithEvenAndOddNumbers_whenRemovingEvenNumbers_thenOddNumbersRemain() {
Queue<Integer> queue = new LinkedList<>();
Queue<Integer> oddElementsQueue = new LinkedList<>();
queue.add(1);
queue.add(2);
queue.add(3);
queue.add(4);
queue.add(5);
while (queue.peek() != null) {
int element = queue.remove();
if (element % 2 != 0) {
oddElementsQueue.add(element);
}
}
assertEquals(3, oddElementsQueue.size());
assertTrue(oddElementsQueue.contains(1));
assertTrue(oddElementsQueue.contains(3));
assertTrue(oddElementsQueue.contains(5));
}
@Test
public void givenStringQueue_whenRemovingStringsThatStartWithA_thenStringElementsRemain() {
Queue<String> queue = new LinkedList<>();
Queue<String> stringElementsQueue = new LinkedList<>();
queue.add("Apple");
queue.add("Banana");
queue.add("Orange");
queue.add("Grape");
queue.add("Mango");
while (queue.peek() != null) {
String element = queue.remove();
if (!element.startsWith("A")) {
stringElementsQueue.add(element);
}
}
assertEquals(4, stringElementsQueue.size());
assertTrue(stringElementsQueue.contains("Banana"));
assertTrue(stringElementsQueue.contains("Orange"));
assertTrue(stringElementsQueue.contains("Grape"));
assertTrue(stringElementsQueue.contains("Mango"));
}
}
package com.baeldung.removequeueelements;
import org.junit.Test;
import java.util.LinkedList;
import java.util.Queue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class RemoveQueueElementsUnitTest {
@Test
public void givenQueueWithEvenAndOddNumbers_whenRemovingEvenNumbers_thenOddNumbersRemain() {
Queue<Integer> queue = new LinkedList<>();
Queue<Integer> oddElementsQueue = new LinkedList<>();
queue.add(1);
queue.add(2);
queue.add(3);
queue.add(4);
queue.add(5);
while (queue.peek() != null) {
int element = queue.remove();
if (element % 2 != 0) {
oddElementsQueue.add(element);
}
}
assertEquals(3, oddElementsQueue.size());
assertTrue(oddElementsQueue.contains(1));
assertTrue(oddElementsQueue.contains(3));
assertTrue(oddElementsQueue.contains(5));
}
@Test
public void givenStringQueue_whenRemovingStringsThatStartWithA_thenStringElementsRemain() {
Queue<String> queue = new LinkedList<>();
Queue<String> stringElementsQueue = new LinkedList<>();
queue.add("Apple");
queue.add("Banana");
queue.add("Orange");
queue.add("Grape");
queue.add("Mango");
while (queue.peek() != null) {
String element = queue.remove();
if (!element.startsWith("A")) {
stringElementsQueue.add(element);
}
}
assertEquals(4, stringElementsQueue.size());
assertTrue(stringElementsQueue.contains("Banana"));
assertTrue(stringElementsQueue.contains("Orange"));
assertTrue(stringElementsQueue.contains("Grape"));
assertTrue(stringElementsQueue.contains("Mango"));
}
}
@@ -0,0 +1,17 @@
package com.baeldung.convertdateandzoneddatetime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Date;
public class DateAndZonedDateTimeConverter {
public static Date convertToDate(ZonedDateTime zonedDateTime) {
return Date.from(zonedDateTime.toInstant());
}
public static ZonedDateTime convertToZonedDateTime(Date date, ZoneId zone) {
return date.toInstant().atZone(zone);
}
}
@@ -0,0 +1,28 @@
package com.baeldung.convertdateandzoneddatetime;
import org.junit.jupiter.api.Test;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Date;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class DateAndZonedDateTimeConverterUnitTest {
@Test
public void givenZonedDateTime_whenConvertToDate_thenCorrect() {
ZonedDateTime zdt = ZonedDateTime.now(ZoneId.of("UTC"));
Date date = DateAndZonedDateTimeConverter.convertToDate(zdt);
assertEquals(Date.from(zdt.toInstant()), date);
}
@Test
public void givenDate_whenConvertToZonedDateTime_thenCorrect() {
Date date = new Date();
ZoneId zoneId = ZoneId.of("UTC");
ZonedDateTime zdt = DateAndZonedDateTimeConverter.convertToZonedDateTime(date, zoneId);
assertEquals(date.toInstant().atZone(zoneId), zdt);
}
}
@@ -10,4 +10,5 @@ This module contains articles about core java exceptions
- [Get the Current Stack Trace in Java](https://www.baeldung.com/java-get-current-stack-trace)
- [Errors and Exceptions in Java](https://www.baeldung.com/java-errors-vs-exceptions)
- [Fix the IllegalArgumentException: No enum const class](https://www.baeldung.com/java-fix-no-enum-const-class)
- [How to Fix EOFException in Java](https://www.baeldung.com/java-fix-eofexception)
- [[<-- Prev]](../core-java-exceptions-3)
@@ -0,0 +1,16 @@
package com.baeldung.exception.eof;
import java.io.DataInputStream;
import java.io.InputStream;
import java.io.ByteArrayInputStream;
public class EOFExceptionDemo {
public static void readInput() throws Exception {
InputStream is = new ByteArrayInputStream("123".getBytes());
DataInputStream in = new DataInputStream(is);
while (true) {
char value = (char)in.readByte();
System.out.println("Input value: " + value);
}
}
}
@@ -0,0 +1,22 @@
package com.baeldung.exception.eof;
import java.io.DataInputStream;
import java.io.InputStream;
import java.io.ByteArrayInputStream;
import java.io.EOFException;
public class EOFExceptionDemo2 {
public static void readInput() throws Exception {
InputStream is = new ByteArrayInputStream("123".getBytes());
DataInputStream in = new DataInputStream(is);
while (true) {
try {
char value = (char)in.readByte();
System.out.println("Input value: " + value);
} catch (EOFException e) {
System.out.println("End of file");
break;
}
}
}
}
@@ -0,0 +1,19 @@
package com.baeldung.exception.eof;
import java.io.DataInputStream;
import java.io.InputStream;
import java.util.Scanner;
import java.io.ByteArrayInputStream;
public class EOFExceptionDemo3 {
public static void readInput() {
InputStream is = new ByteArrayInputStream("1 2 3".getBytes());
Scanner sc = new Scanner(is);
while (sc.hasNextInt()) {
int value = sc.nextInt();
System.out.println("Input value: " + value);
}
System.out.println("End of file");
sc.close();
}
}
@@ -0,0 +1,35 @@
package com.baeldung.exception.eof;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.AfterEach;
import java.io.PrintStream;
import java.io.ByteArrayOutputStream;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class EOFExceptionDemo2UnitTest {
private final PrintStream standardOut = System.out;
private final ByteArrayOutputStream outputStreamCaptor = new ByteArrayOutputStream();
@BeforeEach
public void setUp() {
System.setOut(new PrintStream(outputStreamCaptor));
}
@AfterEach
public void tearDown() {
System.setOut(standardOut);
}
@Test
void readInput()throws Exception {
EOFExceptionDemo2.readInput();
String expectedOuput = "Input value: 1";
expectedOuput += "\n" + "Input value: 2";
expectedOuput += "\n" + "Input value: 3";
expectedOuput += "\n" + "End of file";
assertEquals(expectedOuput, outputStreamCaptor.toString()
.trim());
}
}
@@ -0,0 +1,35 @@
package com.baeldung.exception.eof;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.AfterEach;
import java.io.PrintStream;
import java.io.ByteArrayOutputStream;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class EOFExceptionDemo3UnitTest {
private final PrintStream standardOut = System.out;
private final ByteArrayOutputStream outputStreamCaptor = new ByteArrayOutputStream();
@BeforeEach
public void setUp() {
System.setOut(new PrintStream(outputStreamCaptor));
}
@AfterEach
public void tearDown() {
System.setOut(standardOut);
}
@Test
void readInput() {
EOFExceptionDemo3.readInput();
String expectedOuput = "Input value: 1";
expectedOuput += "\n" + "Input value: 2";
expectedOuput += "\n" + "Input value: 3";
expectedOuput += "\n" + "End of file";
assertEquals(expectedOuput, outputStreamCaptor.toString()
.trim());
}
}
@@ -0,0 +1,36 @@
package com.baeldung.exception.eof;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.AfterEach;
import java.io.EOFException;
import java.io.PrintStream;
import java.io.ByteArrayOutputStream;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class EOFExceptionDemoUnitTest {
private final PrintStream standardOut = System.out;
private final ByteArrayOutputStream outputStreamCaptor = new ByteArrayOutputStream();
@BeforeEach
public void setUp() {
System.setOut(new PrintStream(outputStreamCaptor));
}
@AfterEach
public void tearDown() {
System.setOut(standardOut);
}
@Test
void readInput_throwsEOFException() {
assertThrows(EOFException.class, () -> EOFExceptionDemo.readInput());
String expectedOuput = "Input value: 1";
expectedOuput += "\n" + "Input value: 2";
expectedOuput += "\n" + "Input value: 3";
assertEquals(expectedOuput, outputStreamCaptor.toString()
.trim());
}
}
@@ -6,11 +6,9 @@ This module contains articles about core features in the Java language
- [Convert One Enum to Another Enum in Java](https://www.baeldung.com/java-convert-enums)
- [What Is the Maximum Depth of the Java Call Stack?](https://www.baeldung.com/java-call-stack-max-depth)
- [Get a Random Element From a Set in Java](https://www.baeldung.com/java-set-draw-sample)
- [Stop Executing Further Code in Java](https://www.baeldung.com/java-stop-running-code)
- [Using the Apache Commons Lang 3 for Comparing Objects in Java](https://www.baeldung.com/java-apache-commons-lang-3-compare-objects)
- [Return First Non-null Value in Java](https://www.baeldung.com/java-first-non-null)
- [Compress and Uncompress Byte Array Using Deflater/Inflater](https://www.baeldung.com/java-compress-uncompress-byte-array)
- [Static Final Variables in Java](https://www.baeldung.com/java-static-final-variables)
- [What Is the Error: “Non-static method cannot be referenced from a static context”?](https://www.baeldung.com/java-non-static-method-cannot-be-referenced-from-a-static-context)
- [Recursively Sum the Integers in an Array](https://www.baeldung.com/java-recursive-sum-integer-array)
@@ -0,0 +1,11 @@
## Core Java Lang (Part 7)
This module contains articles about core features in the Java language
### Relevant Articles:
- [Set an Environment Variable at Runtime in Java](https://www.baeldung.com/java-set-environment-variable-runtime)
- [Get a Random Element From a Set in Java](https://www.baeldung.com/java-set-draw-sample)
- [Compress and Uncompress Byte Array Using Deflater/Inflater](https://www.baeldung.com/java-compress-uncompress-byte-array)
[[<-- Prev]](/core-java-modules/core-java-lang-6)
@@ -0,0 +1,70 @@
<?xml version="1.0" encoding="UTF-8"?>
<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>
<artifactId>core-java-lang-7</artifactId>
<packaging>jar</packaging>
<name>core-java-lang-7</name>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.junit-pioneer</groupId>
<artifactId>junit-pioneer</artifactId>
<version>${junit.pioneer.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>testcontainers</artifactId>
<version>${testcontaienr.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>junit-jupiter</artifactId>
<version>${testcontaienr.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<annotationProcessorPaths>
<!-- https://mvnrepository.com/artifact/org.mapstruct/mapstruct-processor -->
<path>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>${mapstruct.version}</version>
</path>
<path>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>${jmh.version}</version>
</path>
</annotationProcessorPaths>
<source>14</source>
<target>14</target>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<junit.pioneer.version>2.2.0</junit.pioneer.version>
<testcontaienr.version>1.19.3</testcontaienr.version>
<mapstruct.version>1.6.0.Beta1</mapstruct.version>
<jmh.version>1.37</jmh.version>
</properties>
</project>
@@ -0,0 +1,42 @@
package com.baeldung.testhashcode;
import org.junit.Test;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import static org.junit.Assert.assertEquals;
public class HahCodeUnitTest {
@Test
public void givenObject_whenTestingHashCodeConsistency_thenConsistentHashCodeReturned() {
MyClass obj = new MyClass("value");
int hashCode1 = obj.hashCode();
int hashCode2 = obj.hashCode();
assertEquals(hashCode1, hashCode2);
}
@Test
public void givenTwoEqualObjects_whenTestingHashCodeEquality_thenEqualHashCodesReturned() {
MyClass obj1 = new MyClass("value");
MyClass obj2 = new MyClass("value");
assertEquals(obj1.hashCode(), obj2.hashCode());
}
@Test
public void givenMultipleObjects_whenTestingHashCodeDistribution_thenEvenDistributionOfHashCodes() {
List<MyClass> objects = new ArrayList<>();
for (int i = 0; i < 1000; i++) {
objects.add(new MyClass("value" + i));
}
Set<Integer> hashCodes = new HashSet<>();
for (MyClass obj : objects) {
hashCodes.add(obj.hashCode());
}
assertEquals(objects.size(), hashCodes.size(), 10);
}
}
@@ -0,0 +1,15 @@
package com.baeldung.testhashcode;
public class MyClass {
private String value;
public MyClass(String value) {
this.value = value;
}
@Override
public int hashCode() {
return value != null ? value.hashCode() : 0;
}
}

Some files were not shown because too many files have changed in this diff Show More