fix conflicts
This commit is contained in:
commit
6d95df0a41
@ -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>
|
||||
|
@ -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);
|
||||
}
|
||||
}
|
||||
|
@ -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};
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -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)
|
||||
|
@ -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>
|
@ -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;
|
||||
}
|
||||
|
||||
}
|
@ -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 |
@ -1,2 +0,0 @@
|
||||
## Relevant Articles
|
||||
- [Implement Connect 4 Game with Java](https://www.baeldung.com/java-connect-4-game)
|
@ -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));
|
||||
}
|
||||
}
|
@ -1,2 +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)
|
@ -0,0 +1,76 @@
|
||||
package com.baeldung.algorithms.eastersunday;
|
||||
|
||||
import java.time.LocalDate;
|
||||
|
||||
public class EasterDateCalculator {
|
||||
|
||||
LocalDate computeEasterDateWithGaussAlgorithm(int year) {
|
||||
int a = year % 19;
|
||||
int b = year % 4;
|
||||
int c = year % 7;
|
||||
int k = year / 100;
|
||||
int p = (13 + 8*k) / 25;
|
||||
int q = k / 4;
|
||||
int M = (15 - p + k - q) % 30;
|
||||
int N = (4 + k - q) % 7;
|
||||
int d = (19*a + M) % 30;
|
||||
int e = (2*b + 4*c + 6*d + N) % 7;
|
||||
|
||||
if (d==29 && e == 6) {
|
||||
return LocalDate.of(year, 4, 19);
|
||||
} else if (d==28 && e==6 && ((11*M + 11)%30 < 10)) {
|
||||
return LocalDate.of(year, 4, 18);
|
||||
}
|
||||
|
||||
int H = 22 + d + e;
|
||||
if (H <= 31) {
|
||||
return LocalDate.of(year, 3, H);
|
||||
}
|
||||
return LocalDate.of(year, 4, H-31);
|
||||
}
|
||||
|
||||
LocalDate computeEasterDateWithButcherMeeusAlgorithm(int year) {
|
||||
int a = year % 19;
|
||||
int b = year / 100;
|
||||
int c = year % 100;
|
||||
int d = b / 4;
|
||||
int e = b % 4;
|
||||
int f = (b + 8) / 25;
|
||||
int g = (b - f + 1) / 3;
|
||||
int h = (19*a + b - d - g + 15) % 30;
|
||||
int i = c / 4;
|
||||
int k = c % 4;
|
||||
int l = (2*e + 2*i - h - k + 32) % 7;
|
||||
int m = (a + 11*h + 22*l) / 451;
|
||||
int t = h + l - 7*m + 114;
|
||||
int n = t / 31;
|
||||
int o = t % 31;
|
||||
return LocalDate.of(year, n, o+1);
|
||||
}
|
||||
|
||||
LocalDate computeEasterDateWithConwayAlgorithm(int year) {
|
||||
int s = year / 100;
|
||||
int t = year % 100;
|
||||
int a = t / 4;
|
||||
int p = s % 4;
|
||||
int x = (9 - 2*p) % 7;
|
||||
int y = (x + t + a) % 7;
|
||||
int g = year % 19;
|
||||
int G = g + 1;
|
||||
int b = s / 4;
|
||||
int r = 8 * (s + 11) / 25;
|
||||
int C = -s + b + r;
|
||||
int d = (11*G + C) % 30;
|
||||
d = (d + 30) % 30;
|
||||
int h = (551 - 19*d + G) / 544;
|
||||
int e = (50 - d - h) % 7;
|
||||
int f = (e + y) % 7;
|
||||
int R = 57 - d - f - h;
|
||||
|
||||
if (R <= 31) {
|
||||
return LocalDate.of(year, 3, R);
|
||||
}
|
||||
return LocalDate.of(year, 4, R-31);
|
||||
}
|
||||
|
||||
}
|
@ -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) {
|
@ -1,23 +1,22 @@
|
||||
package com.baeldung.algorithms.mergeintervals;
|
||||
|
||||
import static java.lang.Integer.max;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
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
|
||||
intervals.sort(Comparator.comparingInt(interval -> interval.start));
|
||||
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);
|
||||
Interval lastMerged = merged.get(merged.size() - 1);
|
||||
if (interval.start <= lastMerged.end){
|
||||
lastMerged.setEnd(max(interval.end, lastMerged.end));
|
||||
} else {
|
||||
merged.add(interval);
|
||||
}
|
||||
@ -25,5 +24,4 @@ public class MergeOverlappingIntervals {
|
||||
|
||||
return merged;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
@ -0,0 +1,53 @@
|
||||
package com.baeldung.algorithms.eastersunday;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.time.LocalDate;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class EasterDateCalculatorUnitTest {
|
||||
|
||||
@Test
|
||||
void givenEasterInMarch_whenComputeEasterDateWithGaussAlgorithm_thenCorrectResult() {
|
||||
assertEquals(LocalDate.of(2024, 3, 31), new EasterDateCalculator().computeEasterDateWithGaussAlgorithm(2024));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenEasterInApril_whenComputeEasterDateWithGaussAlgorithm_thenCorrectResult() {
|
||||
assertEquals(LocalDate.of(2004, 4, 11), new EasterDateCalculator().computeEasterDateWithGaussAlgorithm(2004));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenEdgeCases_whenComputeEasterDateWithGaussAlgorithm_thenCorrectResult() {
|
||||
assertEquals(LocalDate.of(1981, 4, 19), new EasterDateCalculator().computeEasterDateWithGaussAlgorithm(1981));
|
||||
assertEquals(LocalDate.of(1954, 4, 18), new EasterDateCalculator().computeEasterDateWithGaussAlgorithm(1954));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenEasterInMarch_whenComputeEasterDateWithButcherMeeusAlgorithm_thenCorrectResult() {
|
||||
assertEquals(LocalDate.of(2024, 3, 31), new EasterDateCalculator().computeEasterDateWithButcherMeeusAlgorithm(2024));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenEasterInApril_whenComputeEasterDateWithButcherMeeusAlgorithm_thenCorrectResult() {
|
||||
assertEquals(LocalDate.of(2004, 4, 11), new EasterDateCalculator().computeEasterDateWithButcherMeeusAlgorithm(2004));
|
||||
// The following are added just to notice that there is no need for a special case with this algorithm
|
||||
assertEquals(LocalDate.of(1981, 4, 19), new EasterDateCalculator().computeEasterDateWithGaussAlgorithm(1981));
|
||||
assertEquals(LocalDate.of(1954, 4, 18), new EasterDateCalculator().computeEasterDateWithGaussAlgorithm(1954));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenEasterInMarch_whenComputeEasterDateWithConwayAlgorithm_thenCorrectResult() {
|
||||
assertEquals(LocalDate.of(2024, 3, 31), new EasterDateCalculator().computeEasterDateWithConwayAlgorithm(2024));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenEasterInApril_whenComputeEasterDateWithConwayAlgorithm_thenCorrectResult() {
|
||||
assertEquals(LocalDate.of(2004, 4, 11), new EasterDateCalculator().computeEasterDateWithConwayAlgorithm(2004));
|
||||
// The following are added just to notice that there is no need for a special case with this algorithm
|
||||
assertEquals(LocalDate.of(1981, 4, 19), new EasterDateCalculator().computeEasterDateWithGaussAlgorithm(1981));
|
||||
assertEquals(LocalDate.of(1954, 4, 18), new EasterDateCalculator().computeEasterDateWithGaussAlgorithm(1954));
|
||||
}
|
||||
|
||||
}
|
@ -1,30 +1,38 @@
|
||||
package com.baeldung.algorithms.mergeintervals;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
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 List<Interval> intervals = new ArrayList<>(Arrays.asList(
|
||||
// @formatter:off
|
||||
new Interval(3, 5),
|
||||
new Interval(13, 20),
|
||||
new Interval(11, 15),
|
||||
new Interval(15, 16),
|
||||
new Interval(1, 3),
|
||||
new Interval(4, 5),
|
||||
new Interval(16, 17)
|
||||
// @formatter:on
|
||||
));
|
||||
private ArrayList<Interval> intervalsMerged = new ArrayList<>(Arrays.asList(
|
||||
new Interval(1, 5),
|
||||
new Interval(11, 20)
|
||||
private List<Interval> intervalsMerged = new ArrayList<>(Arrays.asList(
|
||||
// @formatter:off
|
||||
new Interval(1, 5),
|
||||
new Interval(11, 20)
|
||||
// @formatter:on
|
||||
));
|
||||
|
||||
@Test
|
||||
void givenIntervals_whenMerging_thenReturnMergedIntervals() {
|
||||
MergeOverlappingIntervals merger = new MergeOverlappingIntervals();
|
||||
ArrayList<Interval> result = (ArrayList<Interval>) merger.doMerge(intervals);
|
||||
assertArrayEquals(intervalsMerged.toArray(), result.toArray());
|
||||
List<Interval> result = merger.doMerge(intervals);
|
||||
assertEquals(intervalsMerged, result);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
@ -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 {
|
||||
|
@ -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)
|
||||
|
||||
|
1
apache-libraries-2/data/inbox/welcome.txt
Normal file
1
apache-libraries-2/data/inbox/welcome.txt
Normal file
@ -0,0 +1 @@
|
||||
Welcome to Baeldung
|
4
apache-libraries-2/data/json/name.json
Normal file
4
apache-libraries-2/data/json/name.json
Normal file
@ -0,0 +1,4 @@
|
||||
{
|
||||
"name" : "phillip",
|
||||
"age" : 5
|
||||
}
|
1
apache-libraries-2/data/outbox/welcome.txt
Normal file
1
apache-libraries-2/data/outbox/welcome.txt
Normal file
@ -0,0 +1 @@
|
||||
WELCOME TO BAELDUNG
|
1
apache-libraries-2/data/output/name.json
Normal file
1
apache-libraries-2/data/output/name.json
Normal file
@ -0,0 +1 @@
|
||||
{"name":"phillip","age":5,"transformedName":"PHILLIP","transformedAge":15}
|
@ -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>
|
@ -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);
|
||||
}
|
||||
}
|
@ -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}");
|
||||
}
|
||||
}
|
@ -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");
|
||||
}
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
@ -1,4 +1,4 @@
|
||||
package dynamicrouter;
|
||||
package com.baeldung.dynamicrouter;
|
||||
|
||||
import com.baeldung.dynamicrouter.DynamicRouterRoute;
|
||||
import org.apache.camel.RoutesBuilder;
|
@ -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>
|
@ -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>
|
||||
|
@ -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>
|
||||
|
@ -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
|
||||
|
@ -0,0 +1,4 @@
|
||||
package com.baeldung;
|
||||
|
||||
public class Unrelated {
|
||||
}
|
@ -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
|
||||
|
@ -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)
|
||||
|
@ -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;
|
||||
}
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
@ -0,0 +1,9 @@
|
||||
package com.baeldung.java21;
|
||||
|
||||
public class StringTemplates {
|
||||
|
||||
public String getStringTemplate() {
|
||||
String name = "Baeldung";
|
||||
return STR."Welcome to \{name}";
|
||||
}
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
@ -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"));
|
||||
}
|
||||
|
||||
}
|
@ -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));
|
||||
}
|
||||
}
|
@ -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());
|
||||
}
|
||||
}
|
@ -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);
|
||||
}
|
||||
}
|
@ -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)
|
||||
|
8
core-java-modules/core-java-8-datetime-3/README.md
Normal file
8
core-java-modules/core-java-8-datetime-3/README.md
Normal 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)
|
55
core-java-modules/core-java-8-datetime-3/pom.xml
Normal file
55
core-java-modules/core-java-8-datetime-3/pom.xml
Normal 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>
|
@ -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) {
|
@ -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) {
|
@ -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));
|
||||
}
|
||||
}
|
@ -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 {
|
||||
|
@ -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);
|
||||
|
@ -0,0 +1,30 @@
|
||||
package com.baeldung.stringtooffsetdatetime;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.time.OffsetDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class StringToOffsetDateTimeUnitTest {
|
||||
String dateTimeString = "2024-04-11T10:15:30+01:00";
|
||||
|
||||
@Test
|
||||
public void givenDateTimeString_whenUsingOffsetDateTimeParse_thenConvertToOffsetDateTime() {
|
||||
OffsetDateTime offsetDateTime = OffsetDateTime.parse(dateTimeString);
|
||||
|
||||
OffsetDateTime expected = OffsetDateTime.of(2024, 4, 11, 10, 15, 30, 0, OffsetDateTime.parse(dateTimeString).getOffset());
|
||||
assertEquals(expected, offsetDateTime);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDateTimeStringAndFormatter_whenUsingDateTimeFormatter_thenConvertToOffsetDateTime() {
|
||||
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssXXX");
|
||||
|
||||
OffsetDateTime offsetDateTime = OffsetDateTime.parse(dateTimeString, formatter);
|
||||
|
||||
OffsetDateTime expected = OffsetDateTime.of(2024, 4, 11, 10, 15, 30, 0, OffsetDateTime.parse(dateTimeString).getOffset());
|
||||
assertEquals(expected, offsetDateTime);
|
||||
}
|
||||
}
|
@ -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"));
|
||||
}
|
||||
}
|
@ -3,3 +3,4 @@
|
||||
- [Find the Equilibrium Indexes of an Array in Java](https://www.baeldung.com/java-equilibrium-index-array)
|
||||
- [Moves Zeros to the End of an Array in Java](https://www.baeldung.com/java-array-sort-move-zeros-end)
|
||||
- [Finding the Majority Element of an Array in Java](https://www.baeldung.com/java-array-find-majority-element)
|
||||
- [Set Matrix Elements to Zero in Java](https://www.baeldung.com/java-set-matrix-elements-to-zero)
|
||||
|
@ -0,0 +1,147 @@
|
||||
package com.baeldung.matrixtozero;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
public class SetMatrixToZero{
|
||||
static void setZeroesByNaiveApproach(int[][] matrix) {
|
||||
int row = matrix.length;
|
||||
int col = matrix[0].length;
|
||||
int [][] result = new int[row][col];
|
||||
|
||||
for(int i = 0; i<row; i++){
|
||||
for(int j = 0; j < col; j++){
|
||||
result[i][j] = matrix[i][j];
|
||||
}
|
||||
}
|
||||
|
||||
for(int i = 0; i < row; i++){
|
||||
for(int j = 0; j < col; j++){
|
||||
if(matrix[i][j] == 0){
|
||||
for(int k = 0; k < col; k++){
|
||||
result[i][k] = 0;
|
||||
}
|
||||
for(int k = 0; k < row; k++){
|
||||
result[k][j] = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for(int i = 0; i < row; i++){
|
||||
for(int j = 0; j < col; j++){
|
||||
matrix[i][j] = result[i][j];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void setZeroesByTimeOptimizedApproach(int[][] matrix) {
|
||||
int rows = matrix.length;
|
||||
int cols = matrix[0].length;
|
||||
|
||||
Set<Integer> rowSet = new HashSet<>();
|
||||
Set<Integer> colSet = new HashSet<>();
|
||||
|
||||
for(int i = 0; i < rows; i++){
|
||||
for(int j = 0; j < cols; j++){
|
||||
if (matrix[i][j] == 0){
|
||||
rowSet.add(i);
|
||||
colSet.add(j);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for(int row: rowSet){
|
||||
for(int j = 0; j < cols; j++){
|
||||
matrix[row][j] = 0;
|
||||
}
|
||||
}
|
||||
|
||||
for(int col: colSet) {
|
||||
for(int i = 0; i < rows; i++){
|
||||
matrix[i][col] = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static boolean hasZeroInFirstRow(int[][] matrix, int cols) {
|
||||
for (int j = 0; j < cols; j++) {
|
||||
if (matrix[0][j] == 0) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
static boolean hasZeroInFirstCol(int[][] matrix, int rows) {
|
||||
for (int i = 0; i < rows; i++) {
|
||||
if (matrix[i][0] == 0) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
static void markZeroesInMatrix(int[][] matrix, int rows, int cols) {
|
||||
for (int i = 1; i < rows; i++) {
|
||||
for (int j = 1; j < cols; j++) {
|
||||
if (matrix[i][j] == 0) {
|
||||
matrix[i][0] = 0;
|
||||
matrix[0][j] = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void setZeroesInRows(int[][] matrix, int rows, int cols) {
|
||||
for (int i = 1; i < rows; i++) {
|
||||
if (matrix[i][0] == 0) {
|
||||
for (int j = 1; j < cols; j++) {
|
||||
matrix[i][j] = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void setZeroesInCols(int[][] matrix, int rows, int cols) {
|
||||
for (int j = 1; j < cols; j++) {
|
||||
if (matrix[0][j] == 0) {
|
||||
for (int i = 1; i < rows; i++) {
|
||||
matrix[i][j] = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void setZeroesInFirstRow(int[][] matrix, int cols) {
|
||||
for (int j = 0; j < cols; j++) {
|
||||
matrix[0][j] = 0;
|
||||
}
|
||||
}
|
||||
|
||||
static void setZeroesInFirstCol(int[][] matrix, int rows) {
|
||||
for (int i = 0; i < rows; i++) {
|
||||
matrix[i][0] = 0;
|
||||
}
|
||||
}
|
||||
|
||||
static void setZeroesByOptimalApproach(int[][] matrix) {
|
||||
int rows = matrix.length;
|
||||
int cols = matrix[0].length;
|
||||
|
||||
boolean firstRowZero = hasZeroInFirstRow(matrix, cols);
|
||||
boolean firstColZero = hasZeroInFirstCol(matrix, rows);
|
||||
|
||||
markZeroesInMatrix(matrix, rows, cols);
|
||||
|
||||
setZeroesInRows(matrix, rows, cols);
|
||||
setZeroesInCols(matrix, rows, cols);
|
||||
|
||||
if (firstRowZero) {
|
||||
setZeroesInFirstRow(matrix, cols);
|
||||
}
|
||||
if (firstColZero) {
|
||||
setZeroesInFirstCol(matrix, rows);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,54 @@
|
||||
package com.baeldung.matrixtozero;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class SetMatrixToZeroUnitTest{
|
||||
@Test
|
||||
void givenMatrix_whenUsingSetZeroesByNaiveApproach_thenSetZeroes() {
|
||||
int[][] matrix = {
|
||||
{1, 2, 3},
|
||||
{4, 0, 6},
|
||||
{7, 8, 9}
|
||||
};
|
||||
int[][] expected = {
|
||||
{1, 0, 3},
|
||||
{0, 0, 0},
|
||||
{7, 0, 9}
|
||||
};
|
||||
SetMatrixToZero.setZeroesByNaiveApproach(matrix);
|
||||
assertArrayEquals(expected, matrix);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenMatrix_whenUsingSetZeroesByTimeOptimizedApproach_thenSetZeroes() {
|
||||
int[][] matrix = {
|
||||
{1, 2, 3},
|
||||
{4, 0, 6},
|
||||
{7, 8, 9}
|
||||
};
|
||||
int[][] expected = {
|
||||
{1, 0, 3},
|
||||
{0, 0, 0},
|
||||
{7, 0, 9}
|
||||
};
|
||||
SetMatrixToZero.setZeroesByTimeOptimizedApproach(matrix);
|
||||
assertArrayEquals(expected, matrix);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenMatrix_whenUsingSetZeroesByOptimalApproach_thenSetZeroes() {
|
||||
int[][] matrix = {
|
||||
{1, 2, 3},
|
||||
{4, 0, 6},
|
||||
{7, 8, 9}
|
||||
};
|
||||
int[][] expected = {
|
||||
{1, 0, 3},
|
||||
{0, 0, 0},
|
||||
{7, 0, 9}
|
||||
};
|
||||
SetMatrixToZero.setZeroesByOptimalApproach(matrix);
|
||||
assertArrayEquals(expected, matrix);
|
||||
}
|
||||
}
|
@ -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)
|
||||
|
@ -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>
|
||||
|
7
core-java-modules/core-java-collections-6/README.md
Normal file
7
core-java-modules/core-java-collections-6/README.md
Normal file
@ -0,0 +1,7 @@
|
||||
=========
|
||||
|
||||
## Core Java Collections Cookbooks and Examples
|
||||
|
||||
### Relevant Articles:
|
||||
|
||||
- More articles: [[<-- prev]](/core-java-modules/core-java-collections-5)
|
71
core-java-modules/core-java-collections-6/pom.xml
Normal file
71
core-java-modules/core-java-collections-6/pom.xml
Normal 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>
|
@ -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);
|
||||
}
|
||||
|
||||
}
|
@ -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);
|
||||
}
|
||||
|
||||
}
|
@ -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)
|
||||
|
@ -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"));
|
||||
}
|
||||
}
|
@ -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"));
|
||||
}
|
||||
}
|
@ -1 +1,2 @@
|
||||
## Relevant Articles:
|
||||
### Relevant Articles:
|
||||
- [Find Map Keys with Duplicate Values in Java](https://www.baeldung.com/java-map-find-keys-repeated-values)
|
||||
|
@ -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)
|
||||
|
@ -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();
|
||||
}
|
||||
|
||||
}
|
@ -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>
|
||||
|
@ -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)
|
||||
|
@ -11,5 +11,6 @@ This module contains articles about core Java input and output (IO)
|
||||
- [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)
|
||||
|
||||
|
@ -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());
|
||||
}
|
||||
}
|
@ -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)
|
||||
|
@ -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>
|
||||
|
@ -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>
|
||||
|
@ -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 Pascal’s 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)
|
||||
|
@ -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)
|
||||
|
@ -12,4 +12,8 @@
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<properties>
|
||||
<java.version>17</java.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
@ -10,3 +10,4 @@ This module contains articles about Object Oriented Programming (OOP) in Java
|
||||
- [Law of Demeter in Java](https://www.baeldung.com/java-demeter-law)
|
||||
- [Java Interface Naming Conventions](https://www.baeldung.com/java-interface-naming-conventions)
|
||||
- [Difference Between Information Hiding and Encapsulation](https://www.baeldung.com/java-information-hiding-vs-encapsulation)
|
||||
- [Statements Before super() in Java](https://www.baeldung.com/java-statements-before-super-constructor)
|
||||
|
@ -0,0 +1,13 @@
|
||||
package com.baeldung.passclassasparameter;
|
||||
|
||||
public class Example {
|
||||
public static void processClass(Class<?> clazz) {
|
||||
System.out.println("Processing class: " + clazz.getName());
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
processClass(String.class);
|
||||
processClass(Integer.class);
|
||||
processClass(Double.class);
|
||||
}
|
||||
}
|
@ -0,0 +1,22 @@
|
||||
package com.baeldung.passclassasparameter;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class GenericExample {
|
||||
public static <T> void printListElements(Class<T> clazz, List<T> list) {
|
||||
System.out.println("Elements of " + clazz.getSimpleName() + " list:");
|
||||
for (T element : list) {
|
||||
System.out.println(element);
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
List<String> stringList = new ArrayList<>();
|
||||
stringList.add("Java");
|
||||
stringList.add("is");
|
||||
stringList.add("awesome");
|
||||
|
||||
printListElements(String.class, stringList);
|
||||
}
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user