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;
}
}
@@ -0,0 +1,121 @@
package com.baeldung.bigdecimalequalvscompare;
import static java.math.RoundingMode.HALF_UP;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.MethodSource;
class BigDecimalEqualityUnitTest {
@ParameterizedTest
@MethodSource("decimalCompareToProvider")
void givenBigDecimals_WhenCompare_ThenGetReasonableResult(BigDecimal fistDecimal,
BigDecimal secondDecimal, boolean areComparablySame) {
assertEquals(fistDecimal.compareTo(secondDecimal) == 0, areComparablySame);
}
@ParameterizedTest
@MethodSource("decimalEqualsProvider")
void givenBigDecimals_WhenCheckEquality_ThenConsiderPrecision(BigDecimal fistDecimal,
BigDecimal secondDecimal, boolean areEqual) {
assertEquals(fistDecimal.equals(secondDecimal), areEqual);
}
@ParameterizedTest
@MethodSource("decimalEqualsProvider")
void givenBigDecimals_WhenCheckEqualityWithoutTrailingZeros_ThenTheSameAsCompareTo(BigDecimal fistDecimal,
BigDecimal secondDecimal) {
BigDecimal strippedFirstDecimal = fistDecimal.stripTrailingZeros();
BigDecimal strippedSecondDecimal = secondDecimal.stripTrailingZeros();
assertEquals(strippedFirstDecimal.equals(strippedSecondDecimal),
strippedFirstDecimal.compareTo(strippedSecondDecimal) == 0);
}
@ParameterizedTest
@MethodSource("decimalProvider")
void givenListOfDecimals_WhenAddingToHashSet_ThenUsingEquals(List<BigDecimal> decimalList) {
Set<BigDecimal> decimalSet = new HashSet<>(decimalList);
assertThat(decimalSet).hasSameElementsAs(decimalList);
}
@ParameterizedTest
@MethodSource("decimalProvider")
void givenListOfDecimals_WhenAddingToSortedSet_ThenUsingCompareTo(List<BigDecimal> decimalList,
List<BigDecimal> expectedDecimalList) {
Set<BigDecimal> decimalSet = new TreeSet<>(decimalList);
assertThat(decimalSet).hasSameElementsAs(expectedDecimalList);
}
@ParameterizedTest
@CsvSource({
"2.0, 2.00",
"4.0, 4.00"
})
void givenNumbersWithDifferentPrecision_WhenPerformingTheSameOperation_TheResultsAreDifferent(
String firstNumber, String secondNumber) {
BigDecimal firstResult = new BigDecimal(firstNumber).divide(BigDecimal.valueOf(3), HALF_UP);
BigDecimal secondResult = new BigDecimal(secondNumber).divide(BigDecimal.valueOf(3), HALF_UP);
assertThat(firstResult).isNotEqualTo(secondResult);
}
static Stream<Arguments> decimalCompareToProvider() {
return Stream.of(
Arguments.of(new BigDecimal("0.1"), new BigDecimal("0.1"), true),
Arguments.of(new BigDecimal("1.1"), new BigDecimal("1.1"), true),
Arguments.of(new BigDecimal("1.10"), new BigDecimal("1.1"), true),
Arguments.of(new BigDecimal("0.100"), new BigDecimal("0.10000"), true),
Arguments.of(new BigDecimal("0.10"), new BigDecimal("0.1000"), true),
Arguments.of(new BigDecimal("0.10"), new BigDecimal("0.1001"), false),
Arguments.of(new BigDecimal("0.10"), new BigDecimal("0.1010"), false),
Arguments.of(new BigDecimal("0.2"), new BigDecimal("0.19999999"), false),
Arguments.of(new BigDecimal("1.0"), new BigDecimal("1.1"), false),
Arguments.of(new BigDecimal("0.01"), new BigDecimal("0.0099999"), false)
);
}
static Stream<Arguments> decimalEqualsProvider() {
return Stream.of(
Arguments.of(new BigDecimal("0.1"), new BigDecimal("0.1"), true),
Arguments.of(new BigDecimal("1.1"), new BigDecimal("1.1"), true),
Arguments.of(new BigDecimal("1.10"), new BigDecimal("1.1"), false),
Arguments.of(new BigDecimal("0.100"), new BigDecimal("0.10000"), false),
Arguments.of(new BigDecimal("0.10"), new BigDecimal("0.1000"), false),
Arguments.of(new BigDecimal("0.10"), new BigDecimal("0.1001"), false),
Arguments.of(new BigDecimal("0.10"), new BigDecimal("0.1010"), false),
Arguments.of(new BigDecimal("0.2"), new BigDecimal("0.19999999"), false),
Arguments.of(new BigDecimal("1.0"), new BigDecimal("1.1"), false),
Arguments.of(new BigDecimal("0.01"), new BigDecimal("0.0099999"), false)
);
}
static Stream<Arguments> decimalProvider() {
return Stream.of(Arguments.of(Arrays.asList(
new BigDecimal("1.1"),
new BigDecimal("1.10"),
new BigDecimal("1.100"),
new BigDecimal("0.10"),
new BigDecimal("0.100"),
new BigDecimal("0.1000"),
new BigDecimal("0.2"),
new BigDecimal("0.20"),
new BigDecimal("0.200")),
Arrays.asList(
new BigDecimal("1.1"),
new BigDecimal("0.10"),
new BigDecimal("0.2"))));
}
}
@@ -0,0 +1,158 @@
package com.baeldung.comparenumbers;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;
class ComparingNumbersOfDifferentClassesUnitTest {
@ValueSource(strings = {"1", "2", "3", "4", "5"})
@ParameterizedTest
void givenSameNumbersButDifferentPrimitives_WhenCheckEquality_ThenTheyEqual(String number) {
int integerNumber = Integer.parseInt(number);
long longNumber = Long.parseLong(number);
assertEquals(longNumber, integerNumber);
}
@ValueSource(strings = {"1", "2", "3", "4", "5"})
@ParameterizedTest
void givenSameNumbersButDifferentPrimitivesWithIntegerOverflow_WhenCheckEquality_ThenTheyNotEqual(String number) {
int integerNumber = Integer.MAX_VALUE + Integer.parseInt(number);
long longNumber = Integer.MAX_VALUE + Long.parseLong(number);
assertNotEquals(longNumber, integerNumber);
}
@ValueSource(strings = {"1", "2", "3", "4", "5"})
@ParameterizedTest
void givenSameNumbersButDifferentPrimitivesTypes_WhenCheckEquality_ThenTheyEqual(String number) {
int integerNumber = Integer.parseInt(number);
double doubleNumber = Double.parseDouble(number);
assertEquals(doubleNumber, integerNumber);
}
@ValueSource(strings = {"1", "2", "3", "4", "5"})
@ParameterizedTest
void givenDifferentNumbersButDifferentPrimitivesTypes_WhenCheckEquality_ThenTheyNotEqual(String number) {
int integerNumber = Integer.parseInt(number);
double doubleNumber = Double.parseDouble(number) + 0.0000000000001;
assertNotEquals(doubleNumber, integerNumber);
}
@Test
void givenSameNumbersButDifferentPrimitivesWithLongOverflow_WhenCheckEquality_ThenTheyEqual() {
long longValue = BigInteger.valueOf(Long.MAX_VALUE)
.add(BigInteger.ONE)
.multiply(BigInteger.TWO).longValue();
int integerValue = BigInteger.valueOf(Long.MAX_VALUE)
.add(BigInteger.ONE).intValue();
assertThat(longValue).isEqualTo(integerValue);
}
@Test
void givenSameNumbersButDifferentPrimitivesWithDoubleOverflow_WhenCheckEquality_ThenTheyEqual() {
double firstDoubleValue = BigDecimal.valueOf(Double.MAX_VALUE).add(BigDecimal.valueOf(42)).doubleValue();
double secondDoubleValue = BigDecimal.valueOf(Double.MAX_VALUE).doubleValue();
assertEquals(firstDoubleValue, secondDoubleValue);
}
@Test
void givenSameNumbersWithDoubleRoundingErrors_WhenCheckEquality_ThenTheyNotEqual() {
double doubleValue = 0.3 / 0.1;
int integerValue = 30 / 10;
assertNotEquals(doubleValue, integerValue);
}
@ValueSource(strings = {"1", "2", "3", "4", "5"})
@ParameterizedTest
void givenSameNumbersButDifferentWrappers_WhenCheckEquality_ThenTheyNotEqual(String number) {
Integer integerNumber = Integer.valueOf(number);
Long longNumber = Long.valueOf(number);
assertNotEquals(longNumber, integerNumber);
}
@ValueSource(strings = {"1", "2", "3", "4", "5"})
@ParameterizedTest
void givenSameNumbersButWrapperTypes_WhenCheckEquality_ThenTheyNotEqual(String number) {
Float floatNumber = Float.valueOf(number);
Integer integerNumber = Integer.valueOf(number);
assertNotEquals(floatNumber, integerNumber);
}
@MethodSource("numbersWithDifferentScaleProvider")
@ParameterizedTest
void givenBigDecimalsWithDifferentScale_WhenCheckEquality_ThenTheyNotEqual(String firstNumber,
String secondNumber) {
BigDecimal firstBigDecimal = new BigDecimal(firstNumber);
BigDecimal secondBigDecimal = new BigDecimal(secondNumber);
assertNotEquals(firstBigDecimal, secondBigDecimal);
}
@MethodSource("numbersWithDifferentScaleProvider")
@ParameterizedTest
void givenBigDecimalsWithDifferentScale_WhenCompare_ThenTheyEqual(String firstNumber,
String secondNumber) {
BigDecimal firstBigDecimal = new BigDecimal(firstNumber);
BigDecimal secondBigDecimal = new BigDecimal(secondNumber);
assertEquals(0, firstBigDecimal.compareTo(secondBigDecimal));
}
@MethodSource("numbersWithDifferentScaleProvider")
@ParameterizedTest
void givenBigDecimalsWithDifferentScale_WhenCompareWithAssertJ_ThenTheyEqual(String firstNumber,
String secondNumber) {
BigDecimal firstBigDecimal = new BigDecimal(firstNumber);
BigDecimal secondBigDecimal = new BigDecimal(secondNumber);
assertThat(firstBigDecimal).isEqualByComparingTo(secondBigDecimal);
}
@MethodSource("numbersWithSameScaleProvider")
@ParameterizedTest
void givenBigDecimalsWithSameScale_WhenCheckEquality_ThenTheyEqual(String firstNumber,
String secondNumber) {
BigDecimal firstBigDecimal = new BigDecimal(firstNumber);
BigDecimal secondBigDecimal = new BigDecimal(secondNumber);
assertEquals(firstBigDecimal, secondBigDecimal);
}
@MethodSource("numbersWithSameScaleProvider")
@ParameterizedTest
void givenBigDecimalsWithSameScale_WhenCompare_ThenTheyEqual(String firstNumber,
String secondNumber) {
BigDecimal firstBigDecimal = new BigDecimal(firstNumber);
BigDecimal secondBigDecimal = new BigDecimal(secondNumber);
assertEquals(0, firstBigDecimal.compareTo(secondBigDecimal));
}
static Stream<Arguments> numbersWithDifferentScaleProvider() {
return Stream.of(
Arguments.of("0", "0.0"), Arguments.of("1", "1.0"),
Arguments.of("2", "2.0"), Arguments.of("3", "3.0"),
Arguments.of("4", "4.0"), Arguments.of("5", "5.0"),
Arguments.of("6", "6.0"), Arguments.of("7", "7.0")
);
}
static Stream<Arguments> numbersWithSameScaleProvider() {
return Stream.of(
Arguments.of("0", "0"), Arguments.of("1", "1"),
Arguments.of("2", "2"), Arguments.of("3", "3"),
Arguments.of("4", "4"), Arguments.of("5", "5"),
Arguments.of("6", "6"), Arguments.of("7", "7")
);
}
}
@@ -6,7 +6,6 @@
- [Check if a String Contains a Number Value in Java](https://www.baeldung.com/java-string-number-presence)
- [Strings Maximum Length in Java](https://www.baeldung.com/java-strings-maximum-length)
- [Javas String.length() and String.getBytes().length](https://www.baeldung.com/java-string-length-vs-getbytes-length)
- [Check If a Java StringBuilder Object Contains a Character](https://www.baeldung.com/java-check-stringbuilder-object-contains-character)
- [Comparing One String With Multiple Values in One Expression in Java](https://www.baeldung.com/java-compare-string-multiple-values-one-expression)
- [Regular Expression for Password Validation in Java](https://www.baeldung.com/java-regex-password-validation)
- [Mask an Email Address and Phone Number in Java](https://www.baeldung.com/java-mask-email-address-phone-number)
@@ -6,4 +6,5 @@
- [UTF-8 Validation in Java](https://www.baeldung.com/java-utf-8-validation)
- [Simple Morse Code Translation in Java](https://www.baeldung.com/java-morse-code-english-translate)
- [How to Determine if a String Contains Invalid Encoded Characters](https://www.baeldung.com/java-check-string-contains-invalid-encoded-characters)
- [Check If a Java StringBuilder Object Contains a Character](https://www.baeldung.com/java-check-stringbuilder-object-contains-character)
- More articles: [[<-- prev]](../core-java-string-operations-8)
@@ -0,0 +1,43 @@
package com.baeldung.LastOccurrenceFinder;
import org.junit.Test;
import java.util.OptionalInt;
import java.util.stream.IntStream;
import static org.junit.Assert.assertEquals;
public class LastOccurrenceFinderUnitTest {
String str = "Welcome to Baeldung";
char target = 'e';
int n = 2;
int expectedIndex = 6;
@Test
public void givenStringAndCharAndN_whenFindingNthLastOccurrence_thenCorrectIndexReturned() {
int count = 0;
int index = -1;
for (int i = str.length() - 1; i >= 0; i--) {
if (str.charAt(i) == target) {
count++;
if (count == n) {
index = i;
break;
}
}
}
assertEquals(expectedIndex, index);
}
@Test
public void givenStringAndCharAndN_whenFindingNthLastOccurrenceUsingStreams_thenCorrectIndexReturned() {
OptionalInt result = IntStream.range(0, str.length())
.map(i -> str.length() - 1 - i)
.filter(i -> str.charAt(i) == target)
.skip(n - 1)
.findFirst();
int index = result.orElse(-1);
assertEquals(expectedIndex, index);
}
}
@@ -0,0 +1,38 @@
package com.baeldung.hashmapcharactercount;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
import static java.util.stream.Collectors.toMap;
import static org.junit.Assert.assertEquals;
public class HashMapCharacterCountUnitTest {
String str = "abcaadcbcb";
@Test
public void givenString_whenUsingStreams_thenVerifyCounts() {
Map<Character, Integer> charCount = str.chars()
.boxed()
.collect(toMap(
k -> (char) k.intValue(),
v -> 1,
Integer::sum));
assertEquals(3, charCount.get('a').intValue());
}
@Test
public void givenString_whenUsingLooping_thenVerifyCounts() {
Map<Character, Integer> charCount = new HashMap<>();
for (char c : str.toCharArray()) {
charCount.merge(c,
1,
Integer::sum);
}
assertEquals(3, charCount.get('a').intValue());
}
}
@@ -2,7 +2,7 @@ package com.baeldung.stringbuilderhaschar;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class CheckIfStringBuilderContainsCharUnitTest {
+1
View File
@@ -144,6 +144,7 @@
<module>core-java-lang-4</module>
<module>core-java-lang-5</module>
<module>core-java-lang-6</module>
<module>core-java-lang-7</module>
<module>core-java-lang-math</module>
<module>core-java-lang-math-2</module>
<module>core-java-lang-math-4</module>