Merge branch 'eugenp:master' into master

This commit is contained in:
sIvanovKonstantyn 2024-04-13 07:13:04 +02:00 committed by GitHub
commit 0dffde16a4
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
833 changed files with 12280 additions and 3250 deletions

View File

@ -5,6 +5,18 @@
<modelVersion>4.0.0</modelVersion>
<artifactId>algorithms-miscellaneous-5</artifactId>
<version>0.0.1-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>17</source>
<target>17</target>
</configuration>
</plugin>
</plugins>
</build>
<name>algorithms-miscellaneous-5</name>
<parent>

View File

@ -1,15 +1,12 @@
package com.baeldung.algorithms.conversion;
import java.math.BigInteger;
import com.google.common.io.BaseEncoding;
import jakarta.xml.bind.DatatypeConverter;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;
import com.google.common.io.BaseEncoding;
import jakarta.xml.bind.DatatypeConverter;
import java.math.BigInteger;
import java.util.HexFormat;
public class HexStringConverter {
@ -109,4 +106,14 @@ public class HexStringConverter {
return BaseEncoding.base16()
.decode(hexString.toUpperCase());
}
public String encodeUsingHexFormat(byte[] bytes) {
HexFormat hexFormat = HexFormat.of();
return hexFormat.formatHex(bytes);
}
public byte[] decodeUsingHexFormat(String hexString) {
HexFormat hexFormat = HexFormat.of();
return hexFormat.parseHex(hexString);
}
}

View File

@ -1,15 +1,13 @@
package com.baeldung.algorithms.conversion;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.apache.commons.codec.DecoderException;
import org.hamcrest.text.IsEqualIgnoringCase;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.baeldung.algorithms.conversion.HexStringConverter;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
class ByteArrayConverterUnitTest {
@ -24,7 +22,7 @@ class ByteArrayConverterUnitTest {
void shouldEncodeByteArrayToHexStringUsingBigIntegerToString() {
byte[] bytes = getSampleBytes();
String hexString = getSampleHexString();
if(hexString.charAt(0) == '0') {
if (hexString.charAt(0) == '0') {
hexString = hexString.substring(1);
}
String output = hexStringConverter.encodeUsingBigIntegerToString(bytes);
@ -46,7 +44,7 @@ class ByteArrayConverterUnitTest {
byte[] output = hexStringConverter.decodeUsingBigInteger(hexString);
assertArrayEquals(bytes, output);
}
@Test
void shouldEncodeByteArrayToHexStringUsingCharacterConversion() {
byte[] bytes = getSampleBytes();
@ -62,7 +60,7 @@ class ByteArrayConverterUnitTest {
byte[] output = hexStringConverter.decodeHexString(hexString);
assertArrayEquals(bytes, output);
}
@Test
void shouldDecodeHexToByteWithInvalidHexCharacter() {
assertThrows(IllegalArgumentException.class, () -> {
@ -118,12 +116,28 @@ class ByteArrayConverterUnitTest {
assertArrayEquals(bytes, output);
}
@Test
void shouldEncodeByteArrayToHexStringUsingHexFormat() throws DecoderException {
byte[] bytes = getSampleBytes();
String hexString = getSampleHexString();
String output = hexStringConverter.encodeUsingHexFormat(bytes);
assertThat(output, IsEqualIgnoringCase.equalToIgnoringCase(hexString));
}
@Test
void shouldDecodeHexStringToByteArrayUsingHexFormat() throws DecoderException {
byte[] bytes = getSampleBytes();
String hexString = getSampleHexString();
byte[] output = hexStringConverter.decodeUsingHexFormat(hexString);
assertArrayEquals(bytes, output);
}
private String getSampleHexString() {
return "0af50c0e2d10";
}
private byte[] getSampleBytes() {
return new byte[] { 10, -11, 12, 14, 45, 16 };
return new byte[]{10, -11, 12, 14, 45, 16};
}
}

View File

@ -10,8 +10,4 @@
- [Check if Two Strings Are Rotations of Each Other](https://www.baeldung.com/java-string-check-strings-rotations)
- [Find the Largest Prime Under the Given Number in Java](https://www.baeldung.com/java-largest-prime-lower-threshold)
- [Count the Number of Unique Digits in an Integer using Java](https://www.baeldung.com/java-int-count-unique-digits)
- [Generate Juggler Sequence in Java](https://www.baeldung.com/java-generate-juggler-sequence)
- [Finding the Parent of a Node in a Binary Search Tree with Java](https://www.baeldung.com/java-find-parent-node-binary-search-tree)
- [Check if a Number Is a Happy Number in Java](https://www.baeldung.com/java-happy-sad-number-test)
- [Find the Largest Number Possible After Removing k Digits of a Number](https://www.baeldung.com/java-find-largest-number-remove-k-digits)
- More articles: [[<-- prev]](/algorithms-miscellaneous-6)

View File

@ -13,4 +13,22 @@
<version>1.0.0-SNAPSHOT</version>
</parent>
<properties>
<jmh.version>1.35</jmh.version>
</properties>
<dependencies>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>${jmh.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>${jmh.version}</version>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,50 @@
package com.baeldung.algorithms.perfectnumber;
import java.util.stream.IntStream;
class PerfectNumber {
public static boolean isPerfectBruteForce(int number) {
int sum = 0;
for (int i = 1; i <= number / 2; i++) {
if (number % i == 0) {
sum += i;
}
}
return sum == number;
}
public static boolean isPerfectStream(int number) {
int sum = IntStream.rangeClosed(2, (int) Math.sqrt(number))
.filter(test -> number % test == 0)
.reduce(1, (s, test) -> s + test + (number / test));
return sum == number;
}
public static boolean isPerfectEuclidEuler(int number) {
int p = 2;
int perfectNumber = (int) (Math.pow(2, p - 1) * (Math.pow(2, p) - 1));
while (perfectNumber <= number) {
if (perfectNumber == number) {
return true;
}
p++;
perfectNumber = (int) (Math.pow(2, p - 1) * (Math.pow(2, p) - 1));
}
return false;
}
public static boolean isPerfectEuclidEulerUsingShift(int number) {
int p = 2;
int perfectNumber = (2 << (p - 1)) * ((2 << p) - 1);
while (perfectNumber <= number) {
if (perfectNumber == number) {
return true;
}
p++;
perfectNumber = (2 << (p - 1)) * ((2 << p) - 1);
}
return false;
}
}

View File

@ -0,0 +1,41 @@
package com.baeldung.algorithms.perfectnumber;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
@State(Scope.Benchmark)
public class PerfectNumberBenchmark {
@Benchmark
public boolean bruteForceBenchmark() {
return PerfectNumber.isPerfectBruteForce(33550336);
}
@Benchmark
public boolean streamBenchmark() {
return PerfectNumber.isPerfectStream(33550336);
}
@Benchmark
public boolean euclidEulerBenchmark() {
return PerfectNumber.isPerfectEuclidEuler(33550336);
}
@Benchmark
public boolean euclidEulerUsingShiftBenchmark() {
return PerfectNumber.isPerfectEuclidEulerUsingShift(33550336);
}
public static void main(String[] args) throws Exception {
Options options = new OptionsBuilder()
.include(PerfectNumberBenchmark.class.getSimpleName())
.forks(1)
.build();
new Runner(options).run();
}
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.1 MiB

After

Width:  |  Height:  |  Size: 160 KiB

View File

@ -1,2 +0,0 @@
## Relevant Articles
- [Implement Connect 4 Game with Java](https://www.baeldung.com/java-connect-4-game)

View File

@ -0,0 +1,68 @@
package com.baeldung.algorithms.perfectnumber;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class PerfectNumberUnitTest {
@Test
void givenPerfectNumber_whenCheckingIsPerfectBruteForce_thenReturnTrue() {
assertTrue(PerfectNumber.isPerfectBruteForce(6));
}
@Test
void givenNonPerfectNumber_whenCheckingIsPerfectBruteForce_thenReturnFalse() {
assertFalse(PerfectNumber.isPerfectBruteForce(10));
}
@Test
void givenNegativeNumber_whenCheckingIsPerfectBruteForce_thenReturnFalse() {
assertFalse(PerfectNumber.isPerfectBruteForce(-28));
}
@Test
void givenPerfectNumber_whenCheckingIsPerfectStream_thenReturnTrue() {
assertTrue(PerfectNumber.isPerfectStream(28));
}
@Test
void givenNonPerfectNumber_whenCheckingIsPerfectStream_thenReturnFalse() {
assertFalse(PerfectNumber.isPerfectStream(10));
}
@Test
void givenNegativeNumber_whenCheckingIsPerfectStream_thenReturnFalse() {
assertFalse(PerfectNumber.isPerfectStream(-6));
}
@Test
void givenPerfectNumber_whenCheckingIsPerfectEuclidEuler_thenReturnTrue() {
assertTrue(PerfectNumber.isPerfectEuclidEuler(28));
}
@Test
void givenNonPerfectNumber_whenCheckingIsPerfectEuclidEuler_thenReturnFalse() {
assertFalse(PerfectNumber.isPerfectEuclidEuler(10));
}
@Test
void givenNegativeNumber_whenCheckingIsPerfectEuclidEuler_thenReturnFalse() {
assertFalse(PerfectNumber.isPerfectEuclidEuler(-6));
}
@Test
void givenPerfectNumber_whenCheckingIsPerfectEuclidEulerUsingShift_thenReturnTrue() {
assertTrue(PerfectNumber.isPerfectEuclidEulerUsingShift(28));
}
@Test
void givenNonPerfectNumber_whenCheckingIsPerfectEuclidEulerUsingShift_thenReturnFalse() {
assertFalse(PerfectNumber.isPerfectEuclidEulerUsingShift(10));
}
@Test
void givenNegativeNumber_whenCheckingIsPerfectEuclidEulerUsingShift_thenReturnFalse() {
assertFalse(PerfectNumber.isPerfectEuclidEulerUsingShift(-6));
}
}

View File

@ -0,0 +1,9 @@
### Relevant Articles:
- [Vigenère Cipher in Java](https://www.baeldung.com/java-vigenere-cipher)
- [Merge Overlapping Intervals in a Java Collection](https://www.baeldung.com/java-collection-merge-overlapping-intervals)
- [Generate Juggler Sequence in Java](https://www.baeldung.com/java-generate-juggler-sequence)
- [Finding the Parent of a Node in a Binary Search Tree with Java](https://www.baeldung.com/java-find-parent-node-binary-search-tree)
- [Check if a Number Is a Happy Number in Java](https://www.baeldung.com/java-happy-sad-number-test)
- [Find the Largest Number Possible After Removing k Digits of a Number](https://www.baeldung.com/java-find-largest-number-remove-k-digits)
- [Implement Connect 4 Game with Java](https://www.baeldung.com/java-connect-4-game)
- More articles: [[<-- prev]](/algorithms-miscellaneous-7)

View File

@ -1,6 +1,6 @@
package com.baeldung.algorithms.largestNumberRemovingK;
import java.util.*;
import java.util.Stack;
public class LargestNumberRemoveKDigits {
public static int findLargestNumberUsingArithmetic(int num, int k) {

View File

@ -0,0 +1,37 @@
package com.baeldung.algorithms.mergeintervals;
import java.util.Objects;
public class Interval {
int start;
int end;
Interval(int start, int end) {
this.start = start;
this.end = end;
}
public void setEnd(int end) {
this.end = end;
}
@Override
public String toString() {
return "Interval{" + "start=" + start + ", end=" + end + '}';
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Interval interval = (Interval) o;
return start == interval.start && end == interval.end;
}
@Override
public int hashCode() {
return Objects.hash(start, end);
}
}

View File

@ -0,0 +1,29 @@
package com.baeldung.algorithms.mergeintervals;
import java.util.ArrayList;
import java.util.List;
public class MergeOverlappingIntervals {
public List<Interval> doMerge(List<Interval> intervals) {
// Sort the intervals based on start time
intervals.sort((one, two) -> one.start - two.start);
// Create somewhere to put the merged list, start it off with the earliest starting interval
ArrayList<Interval> merged = new ArrayList<>();
merged.add(intervals.get(0));
// Loop over each interval and merge if start time is before the end time of the
// previous interval
intervals.forEach(interval -> {
if (merged.get(merged.size() - 1).end > interval.start) {
merged.get(merged.size() - 1).setEnd(interval.end);
} else {
merged.add(interval);
}
});
return merged;
}
}

View File

@ -0,0 +1,11 @@
package com.baeldung.algorithms.skiplist;
class Node {
int value;
Node[] forward; // array to hold references to different levels
public Node(int value, int level) {
this.value = value;
this.forward = new Node[level + 1]; // level + 1 because level is 0-based
}
}

View File

@ -0,0 +1,92 @@
package com.baeldung.algorithms.skiplist;
import java.util.Random;
public class SkipList {
private Node head;
private int maxLevel;
private int level;
private Random random;
public SkipList() {
maxLevel = 16; // maximum number of levels
level = 0; // current level of SkipList
head = new Node(Integer.MIN_VALUE, maxLevel);
random = new Random();
}
public void insert(int value) {
Node[] update = new Node[maxLevel + 1];
Node current = this.head;
for (int i = level; i >= 0; i--) {
while (current.forward[i] != null && current.forward[i].value < value) {
current = current.forward[i];
}
update[i] = current;
}
current = current.forward[0];
if (current == null || current.value != value) {
int lvl = randomLevel();
if (lvl > level) {
for (int i = level + 1; i <= lvl; i++) {
update[i] = head;
}
level = lvl;
}
Node newNode = new Node(value, lvl);
for (int i = 0; i <= lvl; i++) {
newNode.forward[i] = update[i].forward[i];
update[i].forward[i] = newNode;
}
}
}
public boolean search(int value) {
Node current = this.head;
for (int i = level; i >= 0; i--) {
while (current.forward[i] != null && current.forward[i].value < value) {
current = current.forward[i];
}
}
current = current.forward[0];
return current != null && current.value == value;
}
public void delete(int value) {
Node[] update = new Node[maxLevel + 1];
Node current = this.head;
for (int i = level; i >= 0; i--) {
while (current.forward[i] != null && current.forward[i].value < value) {
current = current.forward[i];
}
update[i] = current;
}
current = current.forward[0];
if (current != null && current.value == value) {
for (int i = 0; i <= level; i++) {
if (update[i].forward[i] != current) break;
update[i].forward[i] = current.forward[i];
}
while (level > 0 && head.forward[level] == null) {
level--;
}
}
}
private int randomLevel() {
int lvl = 0;
while (lvl < maxLevel && random.nextDouble() < 0.5) {
lvl++;
}
return lvl;
}
}

View File

@ -0,0 +1,82 @@
package com.baeldung.algorithms.happynumber;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.HashSet;
import java.util.Set;
import org.junit.jupiter.api.Test;
class HappyNumberDecider {
public static boolean isHappyNumber(int n) {
Set<Integer> checkedNumbers = new HashSet<>();
while (true) {
n = sumDigitsSquare(n);
if (n == 1) {
return true;
}
if (checkedNumbers.contains(n)) {
return false;
}
checkedNumbers.add(n);
}
}
public static boolean isHappyNumberFloyd(int n) {
int slow = n;
int fast = n;
do {
slow = sumDigitsSquare(slow);
fast = sumDigitsSquare(sumDigitsSquare(fast));
} while (slow != fast);
return slow == 1;
}
private static int sumDigitsSquare(int n) {
int squareSum = 0;
while (n != 0) {
squareSum += (n % 10) * (n % 10);
n /= 10;
}
return squareSum;
}
}
public class HappyNumberUnitTest {
@Test
void whenUsingIsHappyNumber_thenGetTheExpectedResult() {
assertTrue(HappyNumberDecider.isHappyNumber(7));
assertTrue(HappyNumberDecider.isHappyNumber(10));
assertTrue(HappyNumberDecider.isHappyNumber(13));
assertTrue(HappyNumberDecider.isHappyNumber(19));
assertTrue(HappyNumberDecider.isHappyNumber(23));
assertFalse(HappyNumberDecider.isHappyNumber(4));
assertFalse(HappyNumberDecider.isHappyNumber(6));
assertFalse(HappyNumberDecider.isHappyNumber(11));
assertFalse(HappyNumberDecider.isHappyNumber(15));
assertFalse(HappyNumberDecider.isHappyNumber(20));
}
@Test
void whenUsingIsHappyNumber2_thenGetTheExpectedResult() {
assertTrue(HappyNumberDecider.isHappyNumberFloyd(7));
assertTrue(HappyNumberDecider.isHappyNumberFloyd(10));
assertTrue(HappyNumberDecider.isHappyNumberFloyd(13));
assertTrue(HappyNumberDecider.isHappyNumberFloyd(19));
assertTrue(HappyNumberDecider.isHappyNumberFloyd(23));
assertFalse(HappyNumberDecider.isHappyNumberFloyd(4));
assertFalse(HappyNumberDecider.isHappyNumberFloyd(6));
assertFalse(HappyNumberDecider.isHappyNumberFloyd(11));
assertFalse(HappyNumberDecider.isHappyNumberFloyd(15));
assertFalse(HappyNumberDecider.isHappyNumberFloyd(20));
}
}

View File

@ -0,0 +1,30 @@
package com.baeldung.algorithms.mergeintervals;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import java.util.ArrayList;
import java.util.Arrays;
import org.junit.jupiter.api.Test;
class MergeIntervalsUnitTest {
private ArrayList<Interval> intervals = new ArrayList<>(Arrays.asList(
new Interval(2, 5),
new Interval(13, 20),
new Interval(11, 15),
new Interval(1, 3)
));
private ArrayList<Interval> intervalsMerged = new ArrayList<>(Arrays.asList(
new Interval(1, 5),
new Interval(11, 20)
));
@Test
void givenIntervals_whenMerging_thenReturnMergedIntervals() {
MergeOverlappingIntervals merger = new MergeOverlappingIntervals();
ArrayList<Interval> result = (ArrayList<Interval>) merger.doMerge(intervals);
assertArrayEquals(intervalsMerged.toArray(), result.toArray());
}
}

View File

@ -5,7 +5,9 @@ import org.junit.jupiter.api.Test;
import java.util.NoSuchElementException;
import static org.junit.jupiter.api.Assertions.*;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertNull;
class BinaryTreeParentNodeFinderUnitTest {

View File

@ -0,0 +1,34 @@
package com.baeldung.algorithms.skiplist;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class SkipListUnitTest {
@Test
public void givenSkipList_WhenInsert_ThenSearchFound() {
SkipList skipList = new SkipList();
skipList.insert(3);
assertTrue(skipList.search(3), "Should find 3");
assertFalse(skipList.search(99), "Should not find 99");
}
@Test
public void givenSkipList_WhenDeleteElement_ThenRemoveFromList() {
SkipList skipList = new SkipList();
skipList.insert(3);
skipList.insert(7);
skipList.delete(3);
assertFalse(skipList.search(3), "3 should have been deleted");
skipList.delete(99);
assertTrue(skipList.search(7), "7 should still exist");
}
}

View File

@ -1,5 +1,6 @@
## Relevant Articles
- [Understanding XSLT Processing in Java](https://www.baeldung.com/java-extensible-stylesheet-language-transformations)
- [Add Camel Route at Runtime in Java](https://www.baeldung.com/java-camel-dynamic-route)
- [Logging in Apache Camel](https://www.baeldung.com/java-apache-camel-logging)
- More articles: [[<-- prev]](../apache-libraries)

View File

@ -0,0 +1 @@
Welcome to Baeldung

View File

@ -0,0 +1,4 @@
{
"name" : "phillip",
"age" : 5
}

View File

@ -0,0 +1 @@
WELCOME TO BAELDUNG

View File

@ -0,0 +1 @@
{"name":"phillip","age":5,"transformedName":"PHILLIP","transformedAge":15}

View File

@ -35,11 +35,16 @@
<artifactId>camel-main</artifactId>
<version>${camel.version}</version>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-jackson</artifactId>
<version>${camel.version}</version>
</dependency>
</dependencies>
<properties>
<javax.validation.validation-api.version>2.0.1.Final</javax.validation.validation-api.version>
<camel.version>4.3.0</camel.version>
<camel.version>4.4.1</camel.version>
</properties>
</project>

View File

@ -0,0 +1,13 @@
package com.baeldung.apachecamellogging;
import org.apache.camel.main.Main;
public class CamelLoggingMainApp {
public static void main(String[] args) throws Exception {
Main main = new Main();
main.configure()
.addRoutesBuilder(new FileCopierCamelRoute());
main.run(args);
}
}

View File

@ -0,0 +1,25 @@
package com.baeldung.apachecamellogging;
import org.apache.camel.LoggingLevel;
import org.apache.camel.builder.RouteBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class FileCopierCamelRoute extends RouteBuilder {
private static final Logger LOGGER = LoggerFactory.getLogger(FileCopierCamelRoute.class);
public void configure() {
from("file:data/inbox?noop=true").log("We got an incoming file ${file:name} containing: ${body}")
.to("log:com.baeldung.apachecamellogging?level=INFO")
.process(process -> {
LOGGER.info("We are passing the message to a FileProcesor bean to capitalize the message body");
})
.bean(FileProcessor.class)
.to("file:data/outbox")
.to("log:com.baeldung.apachecamellogging?showBodyType=false&maxChars=20")
.log(LoggingLevel.DEBUG, "Output Process", "The Process ${id}")
.log("Successfully transfer file: ${file:name}");
}
}

View File

@ -0,0 +1,22 @@
package com.baeldung.apachecamellogging;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.model.dataformat.JsonLibrary;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class FileCopierTracerCamelRoute extends RouteBuilder {
Logger logger = LoggerFactory.getLogger(FileCopierTracerCamelRoute.class);
public void configure() {
getContext().setTracing(true);
from("file:data/json?noop=true").to("log:input?level=INFO")
.unmarshal()
.json(JsonLibrary.Jackson)
.bean(FileProcessor.class, "transform")
.marshal()
.json(JsonLibrary.Jackson)
.to("file:data/output");
}
}

View File

@ -0,0 +1,23 @@
package com.baeldung.apachecamellogging;
import org.apache.camel.Body;
import java.util.Map;
public class FileProcessor {
public String process(@Body String fileContent) {
String processedContent = fileContent.toUpperCase();
return processedContent;
}
public Map<String, Object> transform(Map<String, Object> input) {
String name = (String) input.get("name");
int age = (int) input.get("age");
input.put("transformedName", name.toUpperCase());
input.put("transformedAge", age + 10);
return input;
}
}

View File

@ -1,4 +1,4 @@
package dynamicrouter;
package com.baeldung.dynamicrouter;
import com.baeldung.dynamicrouter.DynamicRouterRoute;
import org.apache.camel.RoutesBuilder;

View File

@ -40,6 +40,16 @@
<artifactId>fastexcel-reader</artifactId>
<version>${fastexcel.version}</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>${log4j.version}</version>
</dependency>
</dependencies>
<build>
@ -64,6 +74,7 @@
<jexcel.version>1.0.9</jexcel.version>
<fastexcel.version>0.17.0</fastexcel.version>
<maven.resources.plugin.version>3.3.1</maven.resources.plugin.version>
<log4j.version>2.23.1</log4j.version>
</properties>
</project>

View File

@ -71,7 +71,7 @@
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>${mockito-core.version}</version>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
<dependency>
@ -112,7 +112,6 @@
<feign-core.version>11.2</feign-core.version>
<guice.version>5.1.0</guice.version>
<system-stubs-junit4.version>2.0.2</system-stubs-junit4.version>
<mockito-core.version>4.1.0</mockito-core.version>
<assertj-core.version>3.19.0</assertj-core.version>
<junit-jupiter.version>5.8.1</junit-jupiter.version>
</properties>

View File

@ -11,9 +11,9 @@
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-boot-2</artifactId>
<artifactId>parent-boot-3</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-boot-2</relativePath>
<relativePath>../parent-boot-3</relativePath>
</parent>
<dependencies>
@ -98,7 +98,7 @@
</property>
<property>
<name>spring.datasource.password</name>
<value></value>
<value>test</value>
<!--<value>replace-with-your-password</value> -->
</property>
</appSettings>
@ -113,6 +113,14 @@
<!--</resource> -->
<!--</resources> -->
</configuration>
<dependencies>
<!-- https://mvnrepository.com/artifact/javax.xml.bind/jaxb-api -->
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.4.0-b180830.0359</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>

View File

@ -1,9 +1,9 @@
package com.baeldung.springboot.azure;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
/**
* @author aiet

View File

@ -0,0 +1,4 @@
package com.baeldung;
public class Unrelated {
}

View File

@ -1,7 +1,7 @@
package com.baeldung;
import static org.junit.Assert.assertTrue;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.*;
import java.util.Arrays;
import java.util.Set;
@ -14,22 +14,22 @@ public class OuterUnitTest {
@Test
public void whenGetNestHostFromOuter_thenGetNestHost() {
is(Outer.class.getNestHost().getName()).equals(NEST_HOST_NAME);
assertEquals(NEST_HOST_NAME, Outer.class.getNestHost().getName());
}
@Test
public void whenGetNestHostFromInner_thenGetNestHost() {
is(Outer.Inner.class.getNestHost().getName()).equals(NEST_HOST_NAME);
assertEquals(NEST_HOST_NAME, Outer.Inner.class.getNestHost().getName());
}
@Test
public void whenCheckNestmatesForNestedClasses_thenGetTrue() {
is(Outer.Inner.class.isNestmateOf(Outer.class)).equals(true);
assertTrue(Outer.Inner.class.isNestmateOf(Outer.class));
}
@Test
public void whenCheckNestmatesForUnrelatedClasses_thenGetFalse() {
is(Outer.Inner.class.isNestmateOf(Outer.class)).equals(false);
assertFalse(Outer.Inner.class.isNestmateOf(Unrelated.class));
}
@Test

View File

@ -1,3 +1,4 @@
## Relevant Articles
- [Deprecate Finalization in Java 18](https://www.baeldung.com/java-18-deprecate-finalization)
- [Simple Web Server in Java 18](https://www.baeldung.com/simple-web-server-java-18)
- [Internet Address Resolution SPI in Java](https://www.baeldung.com/java-service-provider-interface)

View File

@ -0,0 +1,44 @@
package com.baeldung.inetspi;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.stream.Stream;
import com.baeldung.inetspi.providers.CustomAddressResolverImpl;
public class InetAddressSPI {
public String usingGetByName(String host) throws UnknownHostException {
InetAddress inetAddress = InetAddress.getByName(host);
return inetAddress.getHostAddress();
}
public String[] usingGetAllByName(String host) throws UnknownHostException {
InetAddress[] inetAddresses = InetAddress.getAllByName(host);
return Arrays.stream(inetAddresses).map(InetAddress::getHostAddress).toArray(String[]::new);
}
public String usingGetByIp(byte[] ip) throws UnknownHostException {
InetAddress inetAddress = InetAddress.getByAddress(ip);
return inetAddress.getHostName();
}
public String usingGetByIpAndReturnsCannonName(byte[] ip) throws UnknownHostException {
InetAddress inetAddress = InetAddress.getByAddress(ip);
return inetAddress.getCanonicalHostName();
}
public String getHostUsingCustomImpl(byte[] ip) throws UnknownHostException {
CustomAddressResolverImpl imp = new CustomAddressResolverImpl();
return imp.get(null).lookupByAddress(ip);
}
public Stream<InetAddress> getIpUsingCustomImpl(String host) throws UnknownHostException {
CustomAddressResolverImpl imp = new CustomAddressResolverImpl();
return imp.get(null).lookupByName(host, null);
}
}

View File

@ -0,0 +1,56 @@
package com.baeldung.inetspi;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.logging.Logger;
import java.util.stream.Stream;
public class Registry {
private final Map<String, List<byte[]>> registry;
private static final Logger LOGGER = Logger.getLogger(Registry.class.getName());
public Registry() {
registry = loadMapWithData();
}
public Stream<InetAddress> getAddressesfromHost(String host) throws UnknownHostException {
LOGGER.info("Performing Forward Lookup for HOST : " + host);
if (!registry.containsKey(host)) {
throw new UnknownHostException("Missing Host information in Resolver");
}
return registry.get(host)
.stream()
.map(add -> constructInetAddress(host, add))
.filter(Objects::nonNull);
}
public String getHostFromAddress(byte[] arr) throws UnknownHostException {
LOGGER.info("Performing Reverse Lookup for Address : " + Arrays.toString(arr));
for (Map.Entry<String, List<byte[]>> entry : registry.entrySet()) {
if (entry.getValue()
.stream()
.anyMatch(ba -> Arrays.equals(ba, arr))) {
return entry.getKey();
}
}
throw new UnknownHostException("Address Not Found");
}
private Map<String, List<byte[]>> loadMapWithData() {
return Map.of("baeldung-local.org", List.of(new byte[] { 1, 2, 3, 4 }));
}
private static InetAddress constructInetAddress(String host, byte[] address) {
try {
return InetAddress.getByAddress(host, address);
} catch (UnknownHostException unknownHostException) {
return null;
}
}
}

View File

@ -0,0 +1,42 @@
package com.baeldung.inetspi.providers;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.net.spi.InetAddressResolver;
import java.net.spi.InetAddressResolverProvider;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import java.util.stream.Stream;
import com.baeldung.inetspi.Registry;
public class CustomAddressResolverImpl extends InetAddressResolverProvider {
private static Logger LOGGER = Logger.getLogger(CustomAddressResolverImpl.class.getName());
private static Registry registry = new Registry();
@Override
public InetAddressResolver get(Configuration configuration) {
LOGGER.info("Using Custom Address Resolver :: " + this.name());
LOGGER.info("Registry initialised");
return new InetAddressResolver() {
@Override
public Stream<InetAddress> lookupByName(String host, LookupPolicy lookupPolicy) throws UnknownHostException {
return registry.getAddressesfromHost(host);
}
@Override
public String lookupByAddress(byte[] addr) throws UnknownHostException {
return registry.getHostFromAddress(addr);
}
};
}
@Override
public String name() {
return "CustomInternetAddressResolverImpl";
}
}

View File

@ -0,0 +1,31 @@
package com.baeldung.inetspi;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.stream.Stream;
import org.junit.Assert;
import org.junit.Test;
public class InetAddressSPIUnitTest {
@Test
public void givenInetAddress_whenUsingInetAddress_thenPerformResolution() throws UnknownHostException {
InetAddressSPI spi = new InetAddressSPI();
Assert.assertNotNull(spi.usingGetByName("www.google.com"));
Assert.assertTrue(spi.usingGetAllByName("www.google.com").length > 1);
Assert.assertNotNull(spi.usingGetByIp(InetAddress.getByName("www.google.com")
.getAddress()));
Assert.assertNotNull(spi.usingGetByIpAndReturnsCannonName(InetAddress.getByName("www.google.com")
.getAddress()));
}
@Test
public void givenCustomInetAddressImplementation_whenUsingInetAddress_thenPerformResolution() throws UnknownHostException {
InetAddressSPI spi = new InetAddressSPI();
Assert.assertEquals("baeldung-local.org", spi.getHostUsingCustomImpl(new byte[] { 1, 2, 3, 4 }));
Stream<InetAddress> response = spi.getIpUsingCustomImpl("baeldung-local.org");
Assert.assertArrayEquals(new byte[] { 1, 2, 3, 4 }, response.findFirst()
.get()
.getAddress());
}
}

View File

@ -0,0 +1,32 @@
package com.baeldung.java21;
public class PatternCaseLabels {
static String processInputOld(String input) {
String output;
switch (input) {
case null -> output = "Oops, null";
case String s -> {
if ("Yes".equalsIgnoreCase(s)) {
output = "It's Yes";
} else if ("No".equalsIgnoreCase(s)) {
output = "It's No";
} else {
output = "Try Again";
}
}
}
return output;
}
static String processInputNew(String input) {
String output;
switch (input) {
case null -> output = "Oops, null";
case String s when "Yes".equalsIgnoreCase(s) -> output = "It's Yes";
case String s when "No".equalsIgnoreCase(s) -> output = "It's No";
case String s -> output = "Try Again";
}
return output;
}
}

View File

@ -0,0 +1,36 @@
package com.baeldung.java21;
public class RecordPattern {
record Point(int x, int y) {}
public static int beforeRecordPattern(Object obj) {
int sum = 0;
if(obj instanceof Point p) {
int x = p.x();
int y = p.y();
sum = x+y;
}
return sum;
}
public static int afterRecordPattern(Object obj) {
if(obj instanceof Point(int x, int y)) {
return x+y;
}
return 0;
}
enum Color {RED, GREEN, BLUE}
record ColoredPoint(Point point, Color color) {}
record RandomPoint(ColoredPoint cp) {}
public static Color getRamdomPointColor(RandomPoint r) {
if(r instanceof RandomPoint(ColoredPoint cp)) {
return cp.color();
}
return null;
}
}

View File

@ -0,0 +1,9 @@
package com.baeldung.java21;
public class StringTemplates {
public String getStringTemplate() {
String name = "Baeldung";
return STR."Welcome to \{name}";
}
}

View File

@ -0,0 +1,56 @@
package com.baeldung.java21;
public class SwitchPattern {
static class Account{
double getBalance() {
return 0;
}
}
static class SavingsAccount extends Account {
@Override
double getBalance() {
return 100;
}
}
static class TermAccount extends Account {
@Override
double getBalance() {
return 1000;
}
}
static class CurrentAccount extends Account {
@Override
double getBalance() {
return 10000;
}
}
static double getBalanceWithOutSwitchPattern(Account account) {
double balance = 0;
if(account instanceof SavingsAccount sa) {
balance = sa.getBalance();
}
else if(account instanceof TermAccount ta) {
balance = ta.getBalance();
}
else if(account instanceof CurrentAccount ca) {
balance = ca.getBalance();
}
return balance;
}
static double getBalanceWithSwitchPattern(Account account) {
double result;
switch (account) {
case null -> throw new IllegalArgumentException("Oops, account is null");
case SavingsAccount sa -> result = sa.getBalance();
case TermAccount ta -> result = ta.getBalance();
case CurrentAccount ca -> result = ca.getBalance();
default -> result = account.getBalance();
}
return result;
}
}

View File

@ -0,0 +1,48 @@
package com.baeldung.java21;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
class PatternCaseLabelsUnitTest {
@Test
void whenProcessInputOldWayWithYes_thenReturnOutput() {
assertEquals("It's Yes", PatternCaseLabels.processInputOld("Yes"));
}
@Test
void whenProcessInputOldWayWithNo_thenReturnOutput() {
assertEquals("It's No", PatternCaseLabels.processInputOld("No"));
}
@Test
void whenProcessInputOldWayWithNull_thenReturnOutput() {
assertEquals("Oops, null", PatternCaseLabels.processInputOld(null));
}
@Test
void whenProcessInputOldWayWithInvalidOption_thenReturnOutput() {
assertEquals("Try Again", PatternCaseLabels.processInputOld("Invalid Option"));
}
@Test
void whenProcessInputNewWayWithYes_thenReturnOutput() {
assertEquals("It's Yes", PatternCaseLabels.processInputNew("Yes"));
}
@Test
void whenProcessInputNewWayWithNo_thenReturnOutput() {
assertEquals("It's No", PatternCaseLabels.processInputNew("No"));
}
@Test
void whenProcessInputNewWayWithNull_thenReturnOutput() {
assertEquals("Oops, null", PatternCaseLabels.processInputNew(null));
}
@Test
void whenProcessInputNewWayWithInvalidOption_thenReturnOutput() {
assertEquals("Try Again", PatternCaseLabels.processInputNew("Invalid Option"));
}
}

View File

@ -0,0 +1,29 @@
package com.baeldung.java21;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
import com.baeldung.java21.RecordPattern.Color;
import com.baeldung.java21.RecordPattern.ColoredPoint;
import com.baeldung.java21.RecordPattern.Point;
import com.baeldung.java21.RecordPattern.RandomPoint;
class RecordPatternUnitTest {
@Test
void whenNoRecordPattern_thenReturnOutput() {
assertEquals(5, RecordPattern.beforeRecordPattern(new Point(2, 3)));
}
@Test
void whenRecordPattern_thenReturnOutput() {
assertEquals(5, RecordPattern.afterRecordPattern(new Point(2, 3)));
}
@Test
void whenRecordPattern_thenReturnColorOutput() {
ColoredPoint coloredPoint = new ColoredPoint(new Point(2, 3), Color.GREEN);
RandomPoint randomPoint = new RandomPoint(coloredPoint);
assertEquals(Color.GREEN, RecordPattern.getRamdomPointColor(randomPoint));
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.java21;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
class StringTemplateUnitTest {
@Test
void whenNoSwitchPattern_thenReturnSavingsAccountBalance() {
StringTemplates stringTemplates = new StringTemplates();
assertEquals("Welcome to Baeldung", stringTemplates.getStringTemplate());
}
}

View File

@ -0,0 +1,19 @@
package com.baeldung.java21;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
class SwitchPatternUnitTest {
@Test
void whenNoSwitchPattern_thenReturnSavingsAccountBalance() {
SwitchPattern.SavingsAccount savingsAccount = new SwitchPattern.SavingsAccount();
assertEquals(100, SwitchPattern.getBalanceWithOutSwitchPattern(savingsAccount), 0);
}
@Test
void whenSwitchPattern_thenReturnSavingsAccountBalance() {
SwitchPattern.SavingsAccount savingsAccount = new SwitchPattern.SavingsAccount();
assertEquals(100, SwitchPattern.getBalanceWithSwitchPattern(savingsAccount), 0);
}
}

View File

@ -9,9 +9,4 @@
- [Round the Date in Java](https://www.baeldung.com/java-round-the-date)
- [Representing Furthest Possible Date in Java](https://www.baeldung.com/java-date-represent-max)
- [Retrieving Unix Time in Java](https://www.baeldung.com/java-retrieve-unix-time)
- [Calculate Months Between Two Dates in Java](https://www.baeldung.com/java-months-difference-two-dates)
- [Format LocalDate to ISO 8601 With T and Z](https://www.baeldung.com/java-format-localdate-iso-8601-t-z)
- [Check if Two Date Ranges Overlap](https://www.baeldung.com/java-check-two-date-ranges-overlap)
- [Difference between ZoneOffset.UTC and ZoneId.of(“UTC”)](https://www.baeldung.com/java-zoneoffset-utc-zoneid-of)
- [Check if a Given Time Lies Between Two Times Regardless of Date](https://www.baeldung.com/java-check-between-two-times)
- [[<-- Prev]](/core-java-modules/core-java-datetime-java8-1)
- [[<-- Prev]](/core-java-modules/core-java-datetime-java8-1) [[Next -->]](/core-java-modules/core-java-8-datetime-3)

View File

@ -0,0 +1,8 @@
### Relevant Articles:
- [Calculate Months Between Two Dates in Java](https://www.baeldung.com/java-months-difference-two-dates)
- [Format LocalDate to ISO 8601 With T and Z](https://www.baeldung.com/java-format-localdate-iso-8601-t-z)
- [Check if Two Date Ranges Overlap](https://www.baeldung.com/java-check-two-date-ranges-overlap)
- [Difference between ZoneOffset.UTC and ZoneId.of(“UTC”)](https://www.baeldung.com/java-zoneoffset-utc-zoneid-of)
- [Check if a Given Time Lies Between Two Times Regardless of Date](https://www.baeldung.com/java-check-between-two-times)
- [[<-- Prev]](/core-java-modules/core-java-8-datetime-2)

View File

@ -0,0 +1,55 @@
<?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-8-datetime-3</artifactId>
<packaging>jar</packaging>
<name>core-java-8-datetime-3</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.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>${joda-time.version}</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<joda-time.version>2.12.5</joda-time.version>
</properties>
</project>

View File

@ -1,11 +1,11 @@
package com.baeldung.daterangeoverlap;
import java.time.LocalDate;
import java.util.Calendar;
import org.joda.time.DateTime;
import org.joda.time.Interval;
import java.time.LocalDate;
import java.util.Calendar;
public class DateRangeOverlapChecker {
public static boolean isOverlapUsingCalendarAndDuration(Calendar start1, Calendar end1, Calendar start2, Calendar end2) {

View File

@ -1,20 +1,16 @@
package com.baeldung.localdatetoiso;
import org.apache.commons.lang3.time.FastDateFormat;
import org.joda.time.DateTimeZone;
import org.joda.time.format.ISODateTimeFormat;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.ISODateTimeFormat;
import org.apache.commons.lang3.time.FastDateFormat;
import java.util.TimeZone;
public class LocalDateToISO {
public String formatUsingDateTimeFormatter(LocalDate localDate) {

View File

@ -1,45 +1,45 @@
package com.baeldung.checkiftimebetweentwotimes;
import org.junit.Test;
import java.time.LocalTime;
import java.util.Calendar;
import java.util.Date;
import static org.junit.Assert.assertTrue;
public class CheckIfTimeBetweenTwoTimesUnitTest {
private LocalTime startTime = LocalTime.parse("09:00:00");
private LocalTime endTime = LocalTime.parse("17:00:00");
private LocalTime targetTime = LocalTime.parse("12:30:00");
@Test
public void givenLocalTime_whenUsingIsAfterIsBefore_thenTimeIsBetween() {
assertTrue(!targetTime.isBefore(startTime) && !targetTime.isAfter(endTime));
}
@Test
public void givenLocalTime_whenUsingCompareTo_thenTimeIsBetween() {
assertTrue(targetTime.compareTo(startTime) >= 0 && targetTime.compareTo(endTime) <= 0);
}
@Test
public void givenDate_whenUsingAfterBefore_thenTimeIsBetween() {
Calendar startCalendar = Calendar.getInstance();
startCalendar.set(Calendar.HOUR_OF_DAY, 9);
startCalendar.set(Calendar.MINUTE, 0);
Date startTime = startCalendar.getTime();
Calendar endCalendar = Calendar.getInstance();
endCalendar.set(Calendar.HOUR_OF_DAY, 17);
endCalendar.set(Calendar.MINUTE, 0);
Date endTime = endCalendar.getTime();
Calendar targetCalendar = Calendar.getInstance();
targetCalendar.set(Calendar.HOUR_OF_DAY, 12);
targetCalendar.set(Calendar.MINUTE, 30);
Date targetTime = targetCalendar.getTime();
assertTrue(!targetTime.before(startTime) && !targetTime.after(endTime));
}
package com.baeldung.checkiftimebetweentwotimes;
import org.junit.Test;
import java.time.LocalTime;
import java.util.Calendar;
import java.util.Date;
import static org.junit.Assert.assertTrue;
public class CheckIfTimeBetweenTwoTimesUnitTest {
private LocalTime startTime = LocalTime.parse("09:00:00");
private LocalTime endTime = LocalTime.parse("17:00:00");
private LocalTime targetTime = LocalTime.parse("12:30:00");
@Test
public void givenLocalTime_whenUsingIsAfterIsBefore_thenTimeIsBetween() {
assertTrue(!targetTime.isBefore(startTime) && !targetTime.isAfter(endTime));
}
@Test
public void givenLocalTime_whenUsingCompareTo_thenTimeIsBetween() {
assertTrue(targetTime.compareTo(startTime) >= 0 && targetTime.compareTo(endTime) <= 0);
}
@Test
public void givenDate_whenUsingAfterBefore_thenTimeIsBetween() {
Calendar startCalendar = Calendar.getInstance();
startCalendar.set(Calendar.HOUR_OF_DAY, 9);
startCalendar.set(Calendar.MINUTE, 0);
Date startTime = startCalendar.getTime();
Calendar endCalendar = Calendar.getInstance();
endCalendar.set(Calendar.HOUR_OF_DAY, 17);
endCalendar.set(Calendar.MINUTE, 0);
Date endTime = endCalendar.getTime();
Calendar targetCalendar = Calendar.getInstance();
targetCalendar.set(Calendar.HOUR_OF_DAY, 12);
targetCalendar.set(Calendar.MINUTE, 30);
Date targetTime = targetCalendar.getTime();
assertTrue(!targetTime.before(startTime) && !targetTime.after(endTime));
}
}

View File

@ -1,13 +1,13 @@
package com.baeldung.daterangeoverlap;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.joda.time.DateTime;
import org.junit.Test;
import java.time.LocalDate;
import java.util.Calendar;
import org.joda.time.DateTime;
import org.junit.Test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class DateRangeOverlapCheckerUnitTest {

View File

@ -1,13 +1,14 @@
package com.baeldung.localdatetoiso;
import org.junit.Test;
import java.time.LocalDate;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import java.time.LocalDate;
public class LocalDateToISOUnitTest {
@Test
void givenLocalDate_whenUsingDateTimeFormatter_thenISOFormat(){
public void givenLocalDate_whenUsingDateTimeFormatter_thenISOFormat(){
LocalDateToISO localDateToISO = new LocalDateToISO();
LocalDate localDate = LocalDate.of(2023, 11, 6);
@ -17,7 +18,7 @@ public class LocalDateToISOUnitTest {
}
@Test
void givenLocalDate_whenUsingSimpleDateFormat_thenISOFormat(){
public void givenLocalDate_whenUsingSimpleDateFormat_thenISOFormat(){
LocalDateToISO localDateToISO = new LocalDateToISO();
LocalDate localDate = LocalDate.of(2023, 11, 6);
@ -27,17 +28,18 @@ public class LocalDateToISOUnitTest {
}
@Test
void givenLocalDate_whenUsingJodaTime_thenISOFormat() {
public void givenLocalDate_whenUsingJodaTime_thenISOFormat() {
LocalDateToISO localDateToISO = new LocalDateToISO();
org.joda.time.LocalDate localDate = new org.joda.time.LocalDate(2023, 11, 6);
String expected = "2023-11-06T00:00:00.000Z";
String actual = localDateToISO.formatUsingJodaTime(localDate);
assertEquals(expected, actual);
assertEquals(expected, actual);
}
@Test
void givenLocalDate_whenUsingApacheCommonsLang_thenISOFormat() {
public void givenLocalDate_whenUsingApacheCommonsLang_thenISOFormat() {
LocalDateToISO localDateToISO = new LocalDateToISO();
LocalDate localDate = LocalDate.of(2023, 11, 6);

View File

@ -1,25 +1,25 @@
package com.baeldung.zoneoffsetandzoneidof;
import org.junit.jupiter.api.Test;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class ZoneOffSetAndZoneIdOfUnitTest {
@Test
public void givenOffsetDateTimeWithUTCZoneOffset_thenOffsetShouldBeUTC() {
OffsetDateTime dateTimeWithOffset = OffsetDateTime.now(ZoneOffset.UTC);
assertEquals(dateTimeWithOffset.getOffset(), ZoneOffset.UTC);
}
@Test
public void givenZonedDateTimeWithUTCZoneId_thenZoneShouldBeUTC() {
ZonedDateTime zonedDateTime = ZonedDateTime.now(ZoneId.of("UTC"));
assertEquals(zonedDateTime.getZone(), ZoneId.of("UTC"));
}
}
package com.baeldung.zoneoffsetandzoneidof;
import org.junit.jupiter.api.Test;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class ZoneOffSetAndZoneIdOfUnitTest {
@Test
public void givenOffsetDateTimeWithUTCZoneOffset_thenOffsetShouldBeUTC() {
OffsetDateTime dateTimeWithOffset = OffsetDateTime.now(ZoneOffset.UTC);
assertEquals(dateTimeWithOffset.getOffset(), ZoneOffset.UTC);
}
@Test
public void givenZonedDateTimeWithUTCZoneId_thenZoneShouldBeUTC() {
ZonedDateTime zonedDateTime = ZonedDateTime.now(ZoneId.of("UTC"));
assertEquals(zonedDateTime.getZone(), ZoneId.of("UTC"));
}
}

View File

@ -9,9 +9,9 @@
- [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)
- [HashSet toArray() Method in Java](https://www.baeldung.com/java-hashset-toarray)
- [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)
- More articles: [[<-- prev]](/core-java-modules/core-java-collections-4)

View File

@ -55,8 +55,8 @@
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>9</source>
<target>9</target>
<source>16</source>
<target>16</target>
</configuration>
</plugin>
</plugins>

View File

@ -0,0 +1,54 @@
package com.baeldung.immutables;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.Test;
class ImmutableCollectionsUnitTest {
@Test
void givenUnmodifiableMap_whenPutNewEntry_thenThrowsUnsupportedOperationException() {
Map<String, String> modifiableMap = new HashMap<>();
modifiableMap.put("name1", "Michael");
modifiableMap.put("name2", "Harry");
Map<String, String> unmodifiableMap = Collections.unmodifiableMap(modifiableMap);
assertThrows(UnsupportedOperationException.class, () -> unmodifiableMap.put("name3", "Micky"));
}
@Test
void givenUnmodifiableMap_whenPutNewEntryUsingOriginalReference_thenSuccess() {
Map<String, String> modifiableMap = new HashMap<>();
modifiableMap.put("name1", "Michael");
modifiableMap.put("name2", "Harry");
Map<String, String> unmodifiableMap = Collections.unmodifiableMap(modifiableMap);
modifiableMap.put("name3", "Micky");
assertEquals(modifiableMap, unmodifiableMap);
assertTrue(unmodifiableMap.containsKey("name3"));
}
@Test
void givenImmutableMap_whenPutNewEntry_thenThrowsUnsupportedOperationException() {
Map<String, String> immutableMap = Map.of("name1", "Michael", "name2", "Harry");
assertThrows(UnsupportedOperationException.class, () -> immutableMap.put("name3", "Micky"));
}
@Test
void givenImmutableMap_whenUsecopyOf_thenExceptionOnPut() {
Map<String, String> immutableMap = Map.of("name1", "Michael", "name2", "Harry");
Map<String, String> copyOfImmutableMap = Map.copyOf(immutableMap);
assertThrows(UnsupportedOperationException.class, () -> copyOfImmutableMap.put("name3", "Micky"));
}
}

View File

@ -0,0 +1,7 @@
=========
## Core Java Collections Cookbooks and Examples
### Relevant Articles:
- More articles: [[<-- prev]](/core-java-modules/core-java-collections-5)

View File

@ -0,0 +1,71 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
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-collections-6</artifactId>
<packaging>jar</packaging>
<name>core-java-collections-6</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.platform</groupId>
<artifactId>junit-platform-runner</artifactId>
<version>${junit-platform.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.roaringbitmap</groupId>
<artifactId>RoaringBitmap</artifactId>
<version>${roaringbitmap.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>${jmh.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>${jmh.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>9</source>
<target>9</target>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<junit.version>5.9.2</junit.version>
<roaringbitmap.version>0.9.38</roaringbitmap.version>
<jmh.version>1.36</jmh.version>
</properties>
</project>

View File

@ -0,0 +1,64 @@
package com.baeldung.iteratorvsforeach;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertIterableEquals;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
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;
class IteratorVsForeachUnitTest {
private static Stream<Arguments> listProvider() {
return Stream.of(Arguments.of(List.of("String1", "String2", "unwanted"), List.of("String1", "String2")));
}
@Test
public void givenEmptyCollection_whenUsingForEach_thenNoElementsAreIterated() {
List<String> names = Collections.emptyList();
StringBuilder stringBuilder = new StringBuilder();
names.forEach(stringBuilder::append);
assertEquals("", stringBuilder.toString());
}
@ParameterizedTest
@MethodSource("listProvider")
public void givenCollectionWithElements_whenRemovingElementDuringForEachIteration_thenElementIsRemoved(List<String> input, List<String> expected) {
List<String> mutableList = new ArrayList<>(input);
// Separate collection for items to be removed
List<String> toRemove = new ArrayList<>();
// Using forEach to identify items to remove
input.forEach(item -> {
if (item.equals("unwanted")) {
toRemove.add(item);
}
});
// Removing the identified items from the original list
mutableList.removeAll(toRemove);
assertIterableEquals(expected, mutableList);
}
@ParameterizedTest
@MethodSource("listProvider")
public void givenCollectionWithElements_whenRemovingElementDuringIteratorIteration_thenElementIsRemoved(List<String> input, List<String> expected) {
List<String> mutableList = new ArrayList<>(input);
Iterator<String> it = mutableList.iterator();
while (it.hasNext()) {
String item = it.next();
if (item.equals("unwanted")) {
it.remove(); // Safely remove item
}
}
assertIterableEquals(expected, mutableList);
}
}

View File

@ -0,0 +1,71 @@
package com.baeldung.listiteration;
import org.junit.jupiter.api.Test;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertIterableEquals;
public class ListIterationUnitTest {
List<String> programmingLanguages = new ArrayList<>(List.of("Java", "Python", "C++"));
List<Integer> numbers = new ArrayList<>(List.of(1, 2, 3));
@Test
public void givenStringList_whenAddElementWithListIterator_thenModifiedList() {
ListIterator<String> listIterator = programmingLanguages.listIterator();
while (listIterator.hasNext()) {
String language = listIterator.next();
if (language.equals("Python")) {
listIterator.add("JavaScript");
}
}
assertIterableEquals(Arrays.asList("Java", "Python", "JavaScript", "C++"), programmingLanguages);
}
@Test
public void givenNumericalList_whenMultiplyElementWithListIterator_thenModifiedList() {
ListIterator<Integer> listIterator = numbers.listIterator();
while (listIterator.hasNext()) {
int num = listIterator.next();
if (num == 2) {
listIterator.add(num * 10);
}
}
assertIterableEquals(Arrays.asList(1, 2, 20, 3), numbers);
}
@Test
public void givenStringList_whenAddElementWithEnhancedForLoopAndCopy_thenModifiedList() {
List<String> copyOfWords = new ArrayList<>(programmingLanguages);
for (String word : copyOfWords) {
programmingLanguages.add(word.toUpperCase()); // Modified: Convert to uppercase
}
assertIterableEquals(Arrays.asList("Java", "Python", "C++", "JAVA", "PYTHON", "C++"), programmingLanguages);
}
@Test
public void givenNumericalList_whenMultiplyElementWithEnhancedForLoopAndCopy_thenModifiedList() {
List<Integer> copyOfNumbers = new ArrayList<>(numbers);
for (int num : copyOfNumbers) {
numbers.add(num * 2);
}
assertIterableEquals(Arrays.asList(1, 2, 3, 2, 4, 6), numbers);
}
@Test
public void givenStringList_whenConvertToUpperCaseWithJava8Stream_thenModifiedList() {
programmingLanguages = programmingLanguages.stream().map(String::toUpperCase).collect(Collectors.toList());
assertIterableEquals(Arrays.asList("JAVA", "PYTHON", "C++"), programmingLanguages);
}
@Test
public void givenNumericalList_whenMultiplyByThreeWithJava8Stream_thenModifiedList() {
numbers = numbers.stream().map(num -> num * 3).collect(Collectors.toList());
assertIterableEquals(Arrays.asList(3, 6, 9), numbers);
}
}

View File

@ -5,3 +5,4 @@ This module contains articles about conversions among Collection types in Java.
### Relevant Articles:
- [Converting HashMap Values to an ArrayList in Java](https://www.baeldung.com/java-hashmap-arraylist)
- [Joining a List<String> in Java With Commas and “and”](https://www.baeldung.com/java-string-concatenation-natural-language)
- [HashSet toArray() Method in Java](https://www.baeldung.com/java-hashset-toarray)

View File

@ -1,59 +0,0 @@
package com.baeldung.java.listInitialization;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import lombok.extern.java.Log;
import org.junit.Assert;
import org.junit.Test;
@Log
public class ListInitializationUnitTest {
@Test
public void givenAnonymousInnerClass_thenInitialiseList() {
List<String> cities = new ArrayList() {
{
add("New York");
add("Rio");
add("Tokyo");
}
};
Assert.assertTrue(cities.contains("New York"));
}
@Test
public void givenArraysAsList_thenInitialiseList() {
List<String> list = Arrays.asList("foo", "bar");
Assert.assertTrue(list.contains("foo"));
}
@Test(expected = UnsupportedOperationException.class)
public void givenArraysAsList_whenAdd_thenUnsupportedException() {
List<String> list = Arrays.asList("foo", "bar");
list.add("baz");
}
@Test
public void givenArraysAsList_whenCreated_thenShareReference() {
String[] array = { "foo", "bar" };
List<String> list = Arrays.asList(array);
array[0] = "baz";
Assert.assertEquals("baz", list.get(0));
}
@Test
public void givenStream_thenInitializeList() {
List<String> list = Stream.of("foo", "bar")
.collect(Collectors.toList());
Assert.assertTrue(list.contains("foo"));
}
}

View File

@ -0,0 +1,91 @@
package com.baeldung.java.listinitialization;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
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.Test;
import lombok.extern.java.Log;
@Log
public class ListInitializationUnitTest {
@Test
public void givenAnonymousInnerClass_thenInitialiseList() {
List<String> cities = new ArrayList() {
{
add("New York");
add("Rio");
add("Tokyo");
}
};
assertTrue(cities.contains("New York"));
}
@Test
public void givenArraysAsList_thenInitialiseList() {
List<String> list = Arrays.asList("foo", "bar");
assertTrue(list.contains("foo"));
}
@Test(expected = UnsupportedOperationException.class)
public void givenArraysAsList_whenAdd_thenUnsupportedException() {
List<String> list = Arrays.asList("foo", "bar");
list.add("baz");
}
@Test
public void givenArraysAsList_whenUsingArrayListConstructor_thenWeCanAddOrRemove() {
List<String> list = new ArrayList<>(Arrays.asList("foo", "bar"));
list.add("baz");
assertEquals(List.of("foo", "bar","baz"), list);
list.remove("baz");
assertEquals(List.of("foo", "bar"), list);
}
@Test
public void givenArraysAsList_whenCreated_thenShareReference() {
String[] array = { "foo", "bar" };
List<String> list = Arrays.asList(array);
array[0] = "baz";
assertEquals("baz", list.get(0));
}
@Test
public void givenIntNumbers_whenRequiredLong_thenCastAutomatically() {
int intNum = 42;
long longNum = intNum;
assertEquals(42L, longNum);
}
@Test
public void givenArrayAsList_whenRequiredLongList_thenGetExpectedResult() {
List<Long> listOfLongFixedSize = Arrays.asList(1L, 2L, 3L);
List<Long> listOfLong = new ArrayList<>(Arrays.asList(1L, 2L, 3L));
List<Long> expected = List.of(1L, 2L, 3L);
assertEquals(expected, listOfLongFixedSize);
assertEquals(expected, listOfLong);
}
@Test
public void givenStream_thenInitializeList() {
List<String> list = Stream.of("foo", "bar")
.collect(Collectors.toList());
assertTrue(list.contains("foo"));
}
}

View File

@ -5,3 +5,4 @@
- [Sorting One List Based on Another List in Java](https://www.baeldung.com/java-sorting-one-list-using-another)
- [Reset ListIterator to First Element of the List in Java](https://www.baeldung.com/java-reset-listiterator)
- [Modify and Print List Items With Java Streams](https://www.baeldung.com/java-stream-list-update-print-elements)
- [Add One Element to an Immutable List in Java](https://www.baeldung.com/java-immutable-list-add-element)

View File

@ -0,0 +1,49 @@
package com.baeldung.addtoimmutablelist;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.junit.jupiter.api.Test;
public class AddElementsToImmutableListUnitTest {
public static <T> List<T> appendAnElement(List<T> immutableList, T element) {
List<T> tmpList = new ArrayList<>(immutableList);
tmpList.add(element);
return Collections.unmodifiableList(tmpList);
}
@SafeVarargs
public static <T> List<T> appendElements(List<T> immutableList, T... elements) {
List<T> tmpList = new ArrayList<>(immutableList);
tmpList.addAll(Arrays.asList(elements));
return Collections.unmodifiableList(tmpList);
}
@Test
void whenCallingAppendAnElement_thenGetExpectedResult() {
List<String> myList = List.of("A", "B", "C", "D", "E");
List<String> expected = List.of("A", "B", "C", "D", "E", "F");
List<String> result = appendAnElement(myList, "F");
assertThat(result).isEqualTo(expected)
.isUnmodifiable();
}
@Test
void whenCallingAppendElements_thenGetExpectedResult() {
List<String> myList = List.of("A", "B", "C", "D", "E");
List<String> expected1 = List.of("A", "B", "C", "D", "E", "F");
List<String> result1 = appendElements(myList, "F");
assertThat(result1).isEqualTo(expected1)
.isUnmodifiable();
List<String> expected2 = List.of("A", "B", "C", "D", "E", "F", "G", "H", "I");
List<String> result2 = appendElements(myList, "F", "G", "H", "I");
assertThat(result2).isEqualTo(expected2)
.isUnmodifiable();
}
}

View File

@ -0,0 +1,2 @@
### Relevant Articles:
- [Find Map Keys with Duplicate Values in Java](https://www.baeldung.com/java-map-find-keys-repeated-values)

View File

@ -0,0 +1,29 @@
<?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-collections-maps-8</artifactId>
<name>core-java-collections-maps-8</name>
<packaging>jar</packaging>
<parent>
<artifactId>core-java-modules</artifactId>
<groupId>com.baeldung.core-java-modules</groupId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<argLine>
--add-opens java.base/java.util=ALL-UNNAMED
</argLine>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,127 @@
package com.baeldung.map.valuetokeyset;
import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.mapping;
import static java.util.stream.Collectors.toSet;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.junit.jupiter.api.Test;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimaps;
import com.google.common.collect.SetMultimap;
public class ConvertMapKeyValueToMapValueKeySetUnitTest {
private static final Map<String, String> INPUT_MAP = Map.of(
// @formatter:off
"Kai", "Linux",
"Eric", "MacOS",
"Kevin", "Windows",
"Liam", "MacOS",
"David", "Linux",
"Saajan", "Windows",
"Loredana", "MacOS"
// @formatter:on
);
private static final Map<String, Set<String>> EXPECTED = Map.of(
// @formatter:off
"Linux", Set.of("Kai", "David"),
"Windows", Set.of("Saajan", "Kevin"),
"MacOS", Set.of("Eric", "Liam", "Loredana")
// @formatter:on
);
private static final Map<String, String> INPUT_MAP_WITH_NULLS = new HashMap<String, String>(INPUT_MAP) {{
put("Tom", null);
put("Jerry", null);
put(null, null);
}};
private static final Map<String, Set<String>> EXPECTED_WITH_NULLS = new HashMap<String, Set<String>>(EXPECTED) {{
put(null, new HashSet<String>() {{
add("Tom");
add("Jerry");
add(null);
}});
}};
public static <K, V> Map<V, Set<K>> transformMap(Map<K, V> input) {
Map<V, Set<K>> resultMap = new HashMap<>();
for (Map.Entry<K, V> entry : input.entrySet()) {
if (!resultMap.containsKey(entry.getValue())) {
resultMap.put(entry.getValue(), new HashSet<>());
}
resultMap.get(entry.getValue())
.add(entry.getKey());
}
return resultMap;
}
@Test
void whenUsingClassicLoopBasedSolution_thenGetExpectedResult() {
Map<String, Set<String>> result = transformMap(INPUT_MAP);
assertEquals(EXPECTED, result);
Map<String, Set<String>> result2 = transformMap(INPUT_MAP_WITH_NULLS);
assertEquals(EXPECTED_WITH_NULLS, result2);
}
@Test
void whenUsingJava8StreamGroupingBy_thenGetExpectedResult() {
Map<String, Set<String>> result = INPUT_MAP.entrySet()
.stream()
.collect(groupingBy(Map.Entry::getValue, mapping(Map.Entry::getKey, toSet())));
assertEquals(EXPECTED, result);
assertThrows(NullPointerException.class, () -> INPUT_MAP_WITH_NULLS.entrySet()
.stream()
.collect(groupingBy(Map.Entry::getValue, mapping(Map.Entry::getKey, toSet()))));
}
@Test
void whenUsingJava8ForEach_thenGetExpectedResult() {
Map<String, Set<String>> result = new HashMap<>();
INPUT_MAP.forEach((key, value) -> result.computeIfAbsent(value, k -> new HashSet<>())
.add(key));
assertEquals(EXPECTED, result);
Map<String, Set<String>> result2 = new HashMap<>();
INPUT_MAP_WITH_NULLS.forEach((key, value) -> result2.computeIfAbsent(value, k -> new HashSet<>())
.add(key));
assertEquals(EXPECTED_WITH_NULLS, result2);
}
@Test
void whenUsingGuavaMultiMapCollector_thenGetExpectedResult() {
Map<String, Set<String>> result = INPUT_MAP.entrySet()
.stream()
.collect(collectingAndThen(Multimaps.toMultimap(Map.Entry::getValue, Map.Entry::getKey, HashMultimap::create), Multimaps::asMap));
assertEquals(EXPECTED, result);
Map<String, Set<String>> result2 = INPUT_MAP_WITH_NULLS.entrySet()
.stream()
.collect(collectingAndThen(Multimaps.toMultimap(Map.Entry::getValue, Map.Entry::getKey, HashMultimap::create), Multimaps::asMap));
assertEquals(EXPECTED_WITH_NULLS, result2);
}
@Test
void whenUsingGuavaInvertFromAndForMap_thenGetExpectedResult() {
SetMultimap<String, String> multiMap = Multimaps.invertFrom(Multimaps.forMap(INPUT_MAP), HashMultimap.create());
Map<String, Set<String>> result = Multimaps.asMap(multiMap);
assertEquals(EXPECTED, result);
SetMultimap<String, String> multiMapWithNulls = Multimaps.invertFrom(Multimaps.forMap(INPUT_MAP_WITH_NULLS), HashMultimap.create());
Map<String, Set<String>> result2 = Multimaps.asMap(multiMapWithNulls);
assertEquals(EXPECTED_WITH_NULLS, result2);
}
}

View File

@ -6,4 +6,5 @@
- [How to Get First Item From a Java Set](https://www.baeldung.com/first-item-set)
- [Cartesian Product of Any Number of Sets in Java](https://www.baeldung.com/java-cartesian-product-sets)
- [How to Get Index of an Item in Java Set](https://www.baeldung.com/java-set-element-find-index)
- [Check if an Element Is Present in a Set in Java](https://www.baeldung.com/java-set-membership)
- More articles: [[<-- prev]](/core-java-modules/core-java-collections-set)

View File

@ -0,0 +1,71 @@
package com.baeldung.checkifpresentinset;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.SetUtils;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
class CheckIfPresentInSetUnitTest {
private static final Set<String> CITIES = new HashSet<>();
@BeforeAll
static void setup() {
CITIES.add("Paris");
CITIES.add("London");
CITIES.add("Tokyo");
CITIES.add("Tamassint");
CITIES.add("New york");
}
@Test
void givenASet_whenUsingStreamAnyMatchMethod_thenCheck() {
boolean isPresent = CITIES.stream()
.anyMatch(city -> city.equals("London"));
assertThat(isPresent).isTrue();
}
@Test
void givenASet_whenUsingStreamFilterMethod_thenCheck() {
long resultCount = CITIES.stream()
.filter(city -> city.equals("Tamassint"))
.count();
assertThat(resultCount).isPositive();
}
@Test
void givenASet_whenUsingContainsMethod_thenCheck() {
assertThat(CITIES.contains("London")).isTrue();
assertThat(CITIES.contains("Madrid")).isFalse();
}
@Test
void givenASet_whenUsingCollectionsDisjointMethod_thenCheck() {
boolean isPresent = !Collections.disjoint(CITIES, Collections.singleton("Paris"));
assertThat(isPresent).isTrue();
}
@Test
void givenASet_whenUsingCollectionUtilsContainsAnyMethod_thenCheck() {
boolean isPresent = CollectionUtils.containsAny(CITIES, Collections.singleton("Paris"));
assertThat(isPresent).isTrue();
}
@Test
void givenASet_whenUsingSetUtilsIntersectionMethod_thenCheck() {
Set<String> result = SetUtils.intersection(CITIES, Collections.singleton("Tamassint"));
assertThat(result).isNotEmpty();
}
}

View File

@ -86,7 +86,7 @@
<maven.compiler.target>1.8</maven.compiler.target>
<jcabi-aspects.version>0.22.6</jcabi-aspects.version>
<aspectjrt.version>1.9.20.1</aspectjrt.version>
<cactoos.version>0.43</cactoos.version>
<cactoos.version>0.55.0</cactoos.version>
<ea-async.version>1.2.3</ea-async.version>
<jcabi-maven-plugin.version>0.14.1</jcabi-maven-plugin.version>
<aspectjtools.version>1.9.20.1</aspectjtools.version>

View File

@ -5,3 +5,4 @@ This module contains articles about converting between Java date and time object
### Relevant Articles:
- [Convert Gregorian to Hijri Date in Java](https://www.baeldung.com/java-date-gregorian-hijri-conversion)
- [Convert String Date to XMLGregorianCalendar in Java](https://www.baeldung.com/java-string-date-xmlgregoriancalendar-conversion)
- [Convert TemporalAccessor to LocalDate](https://www.baeldung.com/java-temporalaccessor-localdate-conversion)

View File

@ -0,0 +1,31 @@
package com.baeldung.TemporalAccessorToLocalDate;
import org.junit.Test;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAccessor;
import java.time.temporal.TemporalQueries;
import static org.junit.Assert.assertEquals;
public class TemporalAccessorToLocalDateUnitTest {
String dateString = "2022-03-28";
TemporalAccessor temporalAccessor = DateTimeFormatter.ISO_LOCAL_DATE.parse(dateString);
@Test
public void givenTemporalAccessor_whenUsingLocalDateFrom_thenConvertToLocalDate() {
LocalDate convertedDate = LocalDate.from(temporalAccessor);
assertEquals(LocalDate.of(2022, 3, 28), convertedDate);
}
@Test
public void givenTemporalAccessor_whenUsingTemporalQueries_thenConvertToLocalDate() {
int year = temporalAccessor.query(TemporalQueries.localDate()).getYear();
int month = temporalAccessor.query(TemporalQueries.localDate()).getMonthValue();
int day = temporalAccessor.query(TemporalQueries.localDate()).getDayOfMonth();
LocalDate convertedDate = LocalDate.of(year, month, day);
assertEquals(LocalDate.of(2022, 3, 28), convertedDate);
}
}

View File

@ -10,5 +10,7 @@ This module contains articles about core Java input and output (IO)
- [Read a File and Split It Into Multiple Files in Java](https://www.baeldung.com/java-read-file-split-into-several)
- [Read and Write Files in Java Using Separate Threads](https://www.baeldung.com/java-read-write-files-different-threads)
- [Convert an OutputStream to a Byte Array in Java](https://www.baeldung.com/java-outputstream-byte-array)
- [Reading a .gz File Line by Line Using GZIPInputStream](https://www.baeldung.com/java-gzipinputstream-read-gz-file-line-by-line)
- [Opening HTML File Using Java](https://www.baeldung.com/java-open-html-file)
- [[<-- Prev]](/core-java-modules/core-java-io-4)

View File

@ -0,0 +1,45 @@
package com.baeldung.openhtmlfiles;
import org.junit.Test;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import static org.junit.Assert.*;
public class OpenHtmlFilesUnitTest {
public URL url;
public String absolutePath;
public OpenHtmlFilesUnitTest() throws URISyntaxException {
url = getClass().getResource("/test.html");
assert url != null;
File file = new File(url.toURI());
if (!file.exists()) {
fail();
}
absolutePath = file.getAbsolutePath();
}
/*
@Test
public void givenHtmlFile_whenUsingDesktopClass_thenOpenFileInDefaultBrowser() throws IOException {
File htmlFile = new File(absolutePath);
Desktop.getDesktop().browse(htmlFile.toURI());
assertTrue(true);
}
*/
@Test
public void givenHtmlFile_whenUsingProcessBuilder_thenOpenFileInDefaultBrowser() throws IOException {
ProcessBuilder pb;
if (System.getProperty("os.name").toLowerCase().contains("win")) {
pb = new ProcessBuilder("cmd.exe", "/c", "start", absolutePath);
} else {
pb = new ProcessBuilder("xdg-open", absolutePath);
}
pb.start();
assertTrue(true);
}
}

View File

@ -0,0 +1,113 @@
package com.baeldung.printwriterwritevsprint;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.io.*;
import java.util.*;
import static org.junit.jupiter.api.Assertions.*;
public class WriteVsPrintUnitTest {
Object outputFromPrintWriter;
Object outputFromPrintWriter() {
try (BufferedReader br = new BufferedReader(new FileReader("output.txt"))){
outputFromPrintWriter = br.readLine();
} catch (IOException e){
e.printStackTrace();
Assertions.fail();
}
return outputFromPrintWriter;
}
@Test
void whenUsingWriteInt_thenASCIICharacterIsPrinted() throws FileNotFoundException {
PrintWriter printWriter = new PrintWriter("output.txt");
printWriter.write(48);
printWriter.close();
assertEquals("0", outputFromPrintWriter());
}
@Test
void whenUsingWriteCharArrayFromOffset_thenCharArrayIsPrinted() throws FileNotFoundException {
PrintWriter printWriter = new PrintWriter("output.txt");
printWriter.write(new char[]{'A','/','&','4','E'}, 1, 4 );
printWriter.close();
assertEquals("/&4E", outputFromPrintWriter());
}
@Test
void whenUsingWriteStringFromOffset_thenLengthOfStringIsPrinted() throws FileNotFoundException {
PrintWriter printWriter = new PrintWriter("output.txt");
printWriter.write("StringExample", 6, 7 );
printWriter.close();
assertEquals("Example", outputFromPrintWriter());
}
@Test
void whenUsingPrintBoolean_thenStringValueIsPrinted() throws FileNotFoundException {
PrintWriter printWriter = new PrintWriter("output.txt");
printWriter.print(true);
printWriter.close();
assertEquals("true", outputFromPrintWriter());
}
@Test
void whenUsingPrintChar_thenCharIsPrinted() throws FileNotFoundException {
PrintWriter printWriter = new PrintWriter("output.txt");
printWriter.print('A');
printWriter.close();
assertEquals("A", outputFromPrintWriter());
}
@Test
void whenUsingPrintInt_thenValueOfIntIsPrinted() throws FileNotFoundException {
PrintWriter printWriter = new PrintWriter("output.txt");
printWriter.print(420);
printWriter.close();
assertEquals("420", outputFromPrintWriter());
}
@Test
void whenUsingPrintString_thenStringIsPrinted() throws FileNotFoundException {
PrintWriter printWriter = new PrintWriter("output.txt");
printWriter.print("RandomString");
printWriter.close();
assertEquals("RandomString", outputFromPrintWriter());
}
@Test
void whenUsingPrintObject_thenObjectToStringIsPrinted() throws FileNotFoundException {
PrintWriter printWriter = new PrintWriter("output.txt");
Map example = new HashMap();
printWriter.print(example);
printWriter.close();
assertEquals(example.toString(), outputFromPrintWriter());
}
}

View File

@ -0,0 +1,15 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>
</title>
</head>
<body>
<h1>Hello dear friend</h1>
</body>
</html>

View File

@ -11,3 +11,5 @@ This module contains articles about core Java input/output(IO) APIs.
- [PrintWriter vs. FileWriter in Java](https://www.baeldung.com/java-printwriter-filewriter-difference)
- [Read Input Character-by-Character in Java](https://www.baeldung.com/java-read-input-character)
- [Difference Between flush() and close() in Java FileWriter](https://www.baeldung.com/java-filewriter-flush-vs-close)
- [Get a Path to a Resource in a Java JAR File](https://www.baeldung.com/java-get-path-resource-jar)
- [Java InputStream vs. InputStreamReader](https://www.baeldung.com/java-inputstream-vs-inputstreamreader)

View File

@ -20,28 +20,6 @@
<version>${lombok.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.7.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
</dependency>
<!-- this is all you need to write tests with JUnit Jupiter -->
<dependency>
<groupId>org.junit.jupiter</groupId>
@ -63,18 +41,6 @@
<version>${junit-jupiter-version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
@ -96,4 +62,5 @@
<properties>
<junit-jupiter-version>5.9.3</junit-jupiter-version>
</properties>
</project>
</project>

View File

@ -0,0 +1,32 @@
package com.baeldung.getpathtoresource;
import org.junit.Test;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Objects;
import static org.junit.Assert.assertNotNull;
public class GetPathToResourceUnitTest {
@Test
public void givenFile_whenClassUsed_thenGetResourcePath() {
URL resourceUrl = GetPathToResourceUnitTest.class.getResource("/sampleText1.txt");
assertNotNull(resourceUrl);
}
@Test
public void givenFile_whenClassLoaderUsed_thenGetResourcePath() {
URL resourceUrl = GetPathToResourceUnitTest.class.getClassLoader().getResource("sampleText1.txt");
assertNotNull(resourceUrl);
}
@Test
public void givenFile_whenPathUsed_thenGetResourcePath() throws Exception {
Path resourcePath = Paths.get(Objects.requireNonNull(GetPathToResourceUnitTest.class.getResource("/sampleText1.txt")).toURI());
assertNotNull(resourcePath);
}
}

View File

@ -0,0 +1,39 @@
package com.baeldung.inputstreamreader;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
public class InputStreamReaderUnitTest {
@Test
public void givenAStringWrittenToAFile_whenReadByInputStreamReader_thenShouldMatchWhenRead(@TempDir Path tempDir) throws IOException {
String sampleTxt = "Good day. This is just a test. Good bye.";
Path sampleOut = tempDir.resolve("sample-out.txt");
List<String> lines = Arrays.asList(sampleTxt);
Files.write(sampleOut, lines);
String absolutePath = String.valueOf(sampleOut.toAbsolutePath());
try (InputStreamReader reader = new InputStreamReader(new FileInputStream(absolutePath), StandardCharsets.UTF_8)) {
boolean isMatched = false;
int b;
StringBuilder sb = new StringBuilder();
while ((b = reader.read()) != -1) {
sb.append((char) b);
if (sb.toString().contains(sampleTxt)) {
isMatched = true;
break;
}
}
assertThat(isMatched).isTrue();
}
}
}

View File

@ -260,7 +260,6 @@
<!-- util -->
<unix4j.version>0.4</unix4j.version>
<grep4j.version>1.8.7</grep4j.version>
<mockito.version>4.6.1</mockito.version>
<!-- maven plugins -->
<javamoney.moneta.version>1.1</javamoney.moneta.version>
<maven-javadoc-plugin.version>3.6.2</maven-javadoc-plugin.version>

View File

@ -7,15 +7,11 @@
- [Evaluating a Math Expression in Java](https://www.baeldung.com/java-evaluate-math-expression-string)
- [Swap Two Variables in Java](https://www.baeldung.com/java-swap-two-variables)
- [Java Program to Find the Roots of a Quadratic Equation](https://www.baeldung.com/roots-quadratic-equation)
- [Create a BMI Calculator in Java](https://www.baeldung.com/java-body-mass-index-calculator)
- [Java Program to Calculate the Standard Deviation](https://www.baeldung.com/java-calculate-standard-deviation)
- [Java Program to Print Pascals Triangle](https://www.baeldung.com/java-pascal-triangle)
- [Java Money and the Currency API](http://www.baeldung.com/java-money-and-currency)
- [Clamp Function in Java](https://www.baeldung.com/java-clamp-function)
- [Creating a Magic Square in Java](https://www.baeldung.com/java-magic-square)
- [Check if a Point Is Between Two Points Drawn on a Straight Line in Java](https://www.baeldung.com/java-check-point-straight-line)
- [Validate if a String Is a Valid Geo Coordinate](https://www.baeldung.com/java-geo-coordinates-validation)
- [Rotate a Vertex Around a Certain Point in Java](https://www.baeldung.com/java-rotate-vertex-around-point)
- [Calculating the Power of Any Number in Java Without Using Math pow() Method](https://www.baeldung.com/java-calculating-the-power-without-math-pow)
- [Solving Rod Cutting Problem in Java](https://www.baeldung.com/java-rod-cutting-problem)
- More articles: [[<-- Prev]](/core-java-modules/core-java-lang-math-2)

View File

@ -2,3 +2,7 @@
### Relevant articles:
- [Calculate Percentiles in Java](https://www.baeldung.com/java-compute-percentiles)
- [Solving Rod Cutting Problem in Java](https://www.baeldung.com/java-rod-cutting-problem)
- [Rotate a Vertex Around a Certain Point in Java](https://www.baeldung.com/java-rotate-vertex-around-point)
- [Create a BMI Calculator in Java](https://www.baeldung.com/java-body-mass-index-calculator)
- [Check if a Point Is Between Two Points Drawn on a Straight Line in Java](https://www.baeldung.com/java-check-point-straight-line)

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