Merge branch 'eugenp:master' into master
This commit is contained in:
@@ -8,4 +8,7 @@
|
||||
- [Find Missing Number From a Given Array in Java](https://www.baeldung.com/java-array-find-missing-number)
|
||||
- [Calculate Weighted Mean in Java](https://www.baeldung.com/java-compute-weighted-average)
|
||||
- [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)
|
||||
- More articles: [[<-- prev]](/algorithms-miscellaneous-6)
|
||||
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
package com.baeldung.algorithms.largestNumberRemovingK;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
public class LargestNumberRemoveKDigits {
|
||||
public static int findLargestNumberUsingArithmetic(int num, int k) {
|
||||
for (int j = 0; j < k; j++) {
|
||||
|
||||
int result = 0;
|
||||
int i = 1;
|
||||
|
||||
while (num / i > 0) {
|
||||
int temp = (num / (i * 10))
|
||||
* i
|
||||
+ (num % i);
|
||||
i *= 10;
|
||||
|
||||
result = Math.max(result, temp);
|
||||
}
|
||||
num = result;
|
||||
}
|
||||
|
||||
return num;
|
||||
}
|
||||
|
||||
public static int findLargestNumberUsingStack(int num, int k) {
|
||||
String numStr = Integer.toString(num);
|
||||
int length = numStr.length();
|
||||
|
||||
if (k == length) return 0;
|
||||
|
||||
Stack<Character> stack = new Stack<>();
|
||||
|
||||
for (int i = 0; i < length; i++) {
|
||||
char digit = numStr.charAt(i);
|
||||
|
||||
while (k > 0 && !stack.isEmpty() && stack.peek() < digit) {
|
||||
stack.pop();
|
||||
k--;
|
||||
}
|
||||
|
||||
stack.push(digit);
|
||||
}
|
||||
|
||||
while (k > 0) {
|
||||
stack.pop();
|
||||
k--;
|
||||
}
|
||||
|
||||
StringBuilder result = new StringBuilder();
|
||||
while (!stack.isEmpty()) {
|
||||
result.insert(0, stack.pop());
|
||||
}
|
||||
|
||||
return Integer.parseInt(result.toString());
|
||||
}
|
||||
}
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
package com.baeldung.algorithms.parentnodebinarytree;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
public class ParentKeeperTreeNode {
|
||||
|
||||
int value;
|
||||
ParentKeeperTreeNode parent;
|
||||
ParentKeeperTreeNode left;
|
||||
ParentKeeperTreeNode right;
|
||||
|
||||
public ParentKeeperTreeNode(int value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (o == null || getClass() != o.getClass()) return false;
|
||||
ParentKeeperTreeNode treeNode = (ParentKeeperTreeNode) o;
|
||||
return value == treeNode.value;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(value);
|
||||
}
|
||||
|
||||
public void insert(int value) {
|
||||
insert(this, value);
|
||||
}
|
||||
|
||||
private void insert(ParentKeeperTreeNode currentNode, final int value) {
|
||||
if (currentNode.left == null && value < currentNode.value) {
|
||||
currentNode.left = new ParentKeeperTreeNode(value);
|
||||
currentNode.left.parent = currentNode;
|
||||
return;
|
||||
}
|
||||
|
||||
if (currentNode.right == null && value > currentNode.value) {
|
||||
currentNode.right = new ParentKeeperTreeNode(value);
|
||||
currentNode.right.parent = currentNode;
|
||||
return;
|
||||
}
|
||||
|
||||
if (value > currentNode.value) {
|
||||
insert(currentNode.right, value);
|
||||
}
|
||||
|
||||
if (value < currentNode.value) {
|
||||
insert(currentNode.left, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
package com.baeldung.algorithms.parentnodebinarytree;
|
||||
|
||||
import java.util.Deque;
|
||||
import java.util.LinkedList;
|
||||
import java.util.NoSuchElementException;
|
||||
import java.util.Objects;
|
||||
|
||||
import static java.lang.String.format;
|
||||
|
||||
public class TreeNode {
|
||||
int value;
|
||||
TreeNode left;
|
||||
TreeNode right;
|
||||
|
||||
public TreeNode(int value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (o == null || getClass() != o.getClass()) return false;
|
||||
TreeNode treeNode = (TreeNode) o;
|
||||
return value == treeNode.value;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(value);
|
||||
}
|
||||
|
||||
public void insert(int value) {
|
||||
insert(this, value);
|
||||
}
|
||||
|
||||
private void insert(TreeNode currentNode, final int value) {
|
||||
if (currentNode.left == null && value < currentNode.value) {
|
||||
currentNode.left = new TreeNode(value);
|
||||
return;
|
||||
}
|
||||
|
||||
if (currentNode.right == null && value > currentNode.value) {
|
||||
currentNode.right = new TreeNode(value);
|
||||
return;
|
||||
}
|
||||
|
||||
if (value > currentNode.value) {
|
||||
insert(currentNode.right, value);
|
||||
}
|
||||
|
||||
if (value < currentNode.value) {
|
||||
insert(currentNode.left, value);
|
||||
}
|
||||
}
|
||||
|
||||
public TreeNode parent(int target) throws NoSuchElementException {
|
||||
return parent(this, new TreeNode(target));
|
||||
}
|
||||
|
||||
private TreeNode parent(TreeNode current, TreeNode target) throws NoSuchElementException {
|
||||
if (target.equals(current) || current == null) {
|
||||
throw new NoSuchElementException(format("No parent node found for 'target.value=%s' " +
|
||||
"The target is not in the tree or the target is the topmost root node.",
|
||||
target.value));
|
||||
}
|
||||
|
||||
if (target.equals(current.left) || target.equals(current.right)) {
|
||||
return current;
|
||||
}
|
||||
|
||||
return parent(target.value < current.value ? current.left : current.right, target);
|
||||
}
|
||||
|
||||
public TreeNode iterativeParent(int target) {
|
||||
return iterativeParent(this, new TreeNode(target));
|
||||
}
|
||||
|
||||
private TreeNode iterativeParent(TreeNode current, TreeNode target) {
|
||||
Deque<TreeNode> parentCandidates = new LinkedList<>();
|
||||
|
||||
String notFoundMessage = format("No parent node found for 'target.value=%s' " +
|
||||
"The target is not in the tree or the target is the topmost root node.",
|
||||
target.value);
|
||||
|
||||
if (target.equals(current)) {
|
||||
throw new NoSuchElementException(notFoundMessage);
|
||||
}
|
||||
|
||||
while (current != null || !parentCandidates.isEmpty()) {
|
||||
|
||||
while (current != null) {
|
||||
parentCandidates.addFirst(current);
|
||||
current = current.left;
|
||||
}
|
||||
|
||||
current = parentCandidates.pollFirst();
|
||||
|
||||
if (target.equals(current.left) || target.equals(current.right)) {
|
||||
return current;
|
||||
}
|
||||
|
||||
current = current.right;
|
||||
}
|
||||
|
||||
throw new NoSuchElementException(notFoundMessage);
|
||||
}
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
package com.baeldung.algorithms.uniquedigit;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
public class UniqueDigitCounter {
|
||||
|
||||
public static int countWithSet(int number) {
|
||||
number = Math.abs(number);
|
||||
Set<Character> uniqueDigits = new HashSet<>();
|
||||
String numberStr = String.valueOf(number);
|
||||
for (char digit : numberStr.toCharArray()) {
|
||||
uniqueDigits.add(digit);
|
||||
}
|
||||
return uniqueDigits.size();
|
||||
}
|
||||
|
||||
public static int countWithBitManipulation(int number) {
|
||||
if (number == 0) {
|
||||
return 1;
|
||||
}
|
||||
number = Math.abs(number);
|
||||
int mask = 0;
|
||||
while (number > 0) {
|
||||
int digit = number % 10;
|
||||
mask |= 1 << digit;
|
||||
number /= 10;
|
||||
}
|
||||
return Integer.bitCount(mask);
|
||||
}
|
||||
|
||||
public static long countWithStreamApi(int number) {
|
||||
return String.valueOf(Math.abs(number)).chars().distinct().count();
|
||||
}
|
||||
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package com.baeldung.algorithms.largestNumberRemovingK;
|
||||
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class LargestNumberRemoveKDigitsUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenNumber_UsingArithmeticRemoveKDigits_thenReturnLargestNumber(){
|
||||
Assertions.assertEquals(LargestNumberRemoveKDigits.findLargestNumberUsingArithmetic(9461, 1), 961);
|
||||
Assertions.assertEquals(LargestNumberRemoveKDigits.findLargestNumberUsingArithmetic(463, 2), 6);
|
||||
Assertions.assertEquals(LargestNumberRemoveKDigits.findLargestNumberUsingArithmetic(98625410, 6), 98);
|
||||
Assertions.assertEquals(LargestNumberRemoveKDigits.findLargestNumberUsingArithmetic(20, 2), 0);
|
||||
Assertions.assertEquals(LargestNumberRemoveKDigits.findLargestNumberUsingArithmetic(98989, 4), 9);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNumber_UsingStackRemoveKDigits_thenReturnLargestNumber(){
|
||||
Assertions.assertEquals(LargestNumberRemoveKDigits.findLargestNumberUsingStack(9461, 1), 961);
|
||||
Assertions.assertEquals(LargestNumberRemoveKDigits.findLargestNumberUsingStack(463, 2), 6);
|
||||
Assertions.assertEquals(LargestNumberRemoveKDigits.findLargestNumberUsingStack(98625410, 6), 98);
|
||||
Assertions.assertEquals(LargestNumberRemoveKDigits.findLargestNumberUsingStack(20, 2), 0);
|
||||
Assertions.assertEquals(LargestNumberRemoveKDigits.findLargestNumberUsingStack(98989, 4), 9);
|
||||
}
|
||||
}
|
||||
+83
@@ -0,0 +1,83 @@
|
||||
package com.baeldung.algorithms.parentnodebinarytree;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.NoSuchElementException;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class BinaryTreeParentNodeFinderUnitTest {
|
||||
|
||||
private TreeNode subject;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
subject = new TreeNode(8);
|
||||
subject.insert(5);
|
||||
subject.insert(12);
|
||||
subject.insert(3);
|
||||
subject.insert(7);
|
||||
subject.insert(1);
|
||||
subject.insert(4);
|
||||
subject.insert(11);
|
||||
subject.insert(14);
|
||||
subject.insert(13);
|
||||
subject.insert(16);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenBinaryTree_whenFindParentNode_thenReturnCorrectParentNode() {
|
||||
assertEquals(8, subject.parent(5).value);
|
||||
assertEquals(5, subject.parent(3).value);
|
||||
assertEquals(5, subject.parent(7).value);
|
||||
assertEquals(3, subject.parent(4).value);
|
||||
assertEquals(3, subject.parent(1).value);
|
||||
assertEquals(8, subject.parent(12).value);
|
||||
assertEquals(12, subject.parent(14).value);
|
||||
assertEquals(12, subject.parent(11).value);
|
||||
assertEquals(14, subject.parent(16).value);
|
||||
assertEquals(14, subject.parent(13).value);
|
||||
assertThrows(NoSuchElementException.class, () -> subject.parent(1231));
|
||||
assertThrows(NoSuchElementException.class, () -> subject.parent(8));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenBinaryTree_whenFindParentNodeIteratively_thenReturnCorrectParentNode() {
|
||||
assertEquals(8, subject.iterativeParent(5).value);
|
||||
assertEquals(5, subject.iterativeParent(3).value);
|
||||
assertEquals(5, subject.iterativeParent(7).value);
|
||||
assertEquals(3, subject.iterativeParent(4).value);
|
||||
assertEquals(3, subject.iterativeParent(1).value);
|
||||
assertEquals(8, subject.iterativeParent(12).value);
|
||||
assertEquals(12, subject.iterativeParent(14).value);
|
||||
assertEquals(12, subject.iterativeParent(11).value);
|
||||
assertEquals(14, subject.iterativeParent(16).value);
|
||||
assertEquals(14, subject.iterativeParent(13).value);
|
||||
assertThrows(NoSuchElementException.class, () -> subject.iterativeParent(1231));
|
||||
assertThrows(NoSuchElementException.class, () -> subject.iterativeParent(8));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenParentKeeperBinaryTree_whenGetParent_thenReturnCorrectParent() {
|
||||
ParentKeeperTreeNode subject = new ParentKeeperTreeNode(8);
|
||||
subject.insert(5);
|
||||
subject.insert(12);
|
||||
subject.insert(3);
|
||||
subject.insert(7);
|
||||
subject.insert(1);
|
||||
subject.insert(4);
|
||||
subject.insert(11);
|
||||
subject.insert(14);
|
||||
subject.insert(13);
|
||||
subject.insert(16);
|
||||
|
||||
assertNull(subject.parent);
|
||||
assertEquals(8, subject.left.parent.value);
|
||||
assertEquals(8, subject.right.parent.value);
|
||||
assertEquals(5, subject.left.left.parent.value);
|
||||
assertEquals(5, subject.left.right.parent.value);
|
||||
|
||||
// tests for other nodes
|
||||
}
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
package com.baeldung.algorithms.uniquedigit;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
public class UniqueDigitCounterUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenNotNegativeNumber_whenCountUniqueDigits_thenCorrectCount() {
|
||||
assertEquals(3, UniqueDigitCounter.countWithSet(122333));
|
||||
assertEquals(1, UniqueDigitCounter.countWithSet(0));
|
||||
assertEquals(2, UniqueDigitCounter.countWithSet(101));
|
||||
|
||||
assertEquals(3, UniqueDigitCounter.countWithBitManipulation(122333));
|
||||
assertEquals(1, UniqueDigitCounter.countWithBitManipulation(0));
|
||||
assertEquals(2, UniqueDigitCounter.countWithBitManipulation(101));
|
||||
|
||||
assertEquals(3, UniqueDigitCounter.countWithStreamApi(122333));
|
||||
assertEquals(1, UniqueDigitCounter.countWithStreamApi(0));
|
||||
assertEquals(2, UniqueDigitCounter.countWithStreamApi(101));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNegativeNumber_whenCountUniqueDigits_thenCorrectCount() {
|
||||
assertEquals(3, UniqueDigitCounter.countWithSet(-122333));
|
||||
assertEquals(3, UniqueDigitCounter.countWithBitManipulation(-122333));
|
||||
assertEquals(3, UniqueDigitCounter.countWithStreamApi(-122333));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLargeNumber_whenCountUniqueDigits_thenCorrectCount() {
|
||||
assertEquals(2, UniqueDigitCounter.countWithSet(1000000000));
|
||||
assertEquals(2, UniqueDigitCounter.countWithBitManipulation(1000000000));
|
||||
assertEquals(2, UniqueDigitCounter.countWithStreamApi(1000000000));
|
||||
}
|
||||
|
||||
}
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
package com.baeldung.algorithms.vigenere;
|
||||
|
||||
public class VigenereCipher {
|
||||
private final String characters;
|
||||
|
||||
public VigenereCipher() {
|
||||
this("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
|
||||
}
|
||||
|
||||
public VigenereCipher(String characters) {
|
||||
this.characters = characters;
|
||||
}
|
||||
|
||||
public String encode(String input, String key) {
|
||||
String result = "";
|
||||
|
||||
int keyPosition = 0;
|
||||
for (char c : input.toCharArray()) {
|
||||
char k = key.charAt(keyPosition % key.length());
|
||||
|
||||
int charIndex = characters.indexOf(c);
|
||||
int keyIndex = characters.indexOf(k);
|
||||
|
||||
if (charIndex >= 0) {
|
||||
if (keyIndex >= 0) {
|
||||
int newCharIndex = (charIndex + keyIndex + 1) % characters.length();
|
||||
c = characters.charAt(newCharIndex);
|
||||
|
||||
}
|
||||
|
||||
keyPosition++;
|
||||
}
|
||||
|
||||
result += c;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public String decode(String input, String key) {
|
||||
String result = "";
|
||||
|
||||
int keyPosition = 0;
|
||||
for (char c : input.toCharArray()) {
|
||||
char k = key.charAt(keyPosition % key.length());
|
||||
|
||||
int charIndex = characters.indexOf(c);
|
||||
int keyIndex = characters.indexOf(k);
|
||||
|
||||
if (charIndex >= 0) {
|
||||
if (keyIndex >= 0) {
|
||||
int newCharIndex = charIndex - keyIndex - 1;
|
||||
if (newCharIndex < 0) {
|
||||
newCharIndex = characters.length() + newCharIndex;
|
||||
}
|
||||
c = characters.charAt(newCharIndex);
|
||||
|
||||
}
|
||||
|
||||
keyPosition++;
|
||||
}
|
||||
|
||||
result += c;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
}
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
package com.baeldung.algorithms.vigenere;
|
||||
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class VigenereCipherUnitTest {
|
||||
|
||||
@Test
|
||||
void encodeBaeldung() {
|
||||
VigenereCipher cipher = new VigenereCipher();
|
||||
String output = cipher.encode("BAELDUNG", "HELLO");
|
||||
|
||||
Assertions.assertEquals("JFQXSCSS", output);
|
||||
}
|
||||
|
||||
@Test
|
||||
void encodeBaeldungMixedCharacters() {
|
||||
VigenereCipher cipher = new VigenereCipher("JQFVHPWORZSLNMKYCGBUXIEDTA");
|
||||
String output = cipher.encode("BAELDUNG", "HELLO");
|
||||
|
||||
Assertions.assertEquals("DERDPTZV", output);
|
||||
}
|
||||
|
||||
@Test
|
||||
void encodeArticleTitle() {
|
||||
VigenereCipher cipher = new VigenereCipher();
|
||||
String output = cipher.encode("VEGENERE CIPHER IN JAVA", "BAELDUNG");
|
||||
|
||||
Assertions.assertEquals("XFLQRZFL EJUTIM WU LBAM", output);
|
||||
}
|
||||
|
||||
@Test
|
||||
void encodeArticleTitleMoreCharacters() {
|
||||
VigenereCipher cipher = new VigenereCipher("ABCDEFGHIJKLMNOPQRSTUVWXYZ ");
|
||||
String output = cipher.encode("VEGENERE CIPHER IN JAVA", "BAELDUNG");
|
||||
|
||||
Assertions.assertEquals("XFLQRZELBDNALZEGKOEVEPO", output);
|
||||
}
|
||||
|
||||
@Test
|
||||
void decodeBaeldung() {
|
||||
VigenereCipher cipher = new VigenereCipher();
|
||||
String output = cipher.decode("JFQXSCSS", "HELLO");
|
||||
|
||||
Assertions.assertEquals("BAELDUNG", output);
|
||||
}
|
||||
|
||||
@Test
|
||||
void decodeBaeldungMixedCharacters() {
|
||||
VigenereCipher cipher = new VigenereCipher("JQFVHPWORZSLNMKYCGBUXIEDTA");
|
||||
String output = cipher.decode("DERDPTZV", "HELLO");
|
||||
|
||||
Assertions.assertEquals("BAELDUNG", output);
|
||||
}
|
||||
|
||||
@Test
|
||||
void decodeArticleTitleMoreCharacters() {
|
||||
VigenereCipher cipher = new VigenereCipher("ABCDEFGHIJKLMNOPQRSTUVWXYZ ");
|
||||
String output = cipher.decode("XFLQRZELBDNALZEGKOEVEPO", "BAELDUNG");
|
||||
|
||||
Assertions.assertEquals("VEGENERE CIPHER IN JAVA", output);
|
||||
}
|
||||
}
|
||||
@@ -82,7 +82,7 @@
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-oxm</artifactId>
|
||||
<version>${spring.version}</version>
|
||||
<version>${spring-oxm.version}</version>
|
||||
</dependency>
|
||||
<!-- marshalling -->
|
||||
<dependency>
|
||||
@@ -233,6 +233,7 @@
|
||||
</profiles>
|
||||
|
||||
<properties>
|
||||
<spring-oxm.version>6.1.4</spring-oxm.version>
|
||||
<!-- util -->
|
||||
<commons-codec.version>1.16.0</commons-codec.version>
|
||||
<httpasyncclient.version>4.1.5</httpasyncclient.version>
|
||||
|
||||
@@ -20,6 +20,12 @@
|
||||
<artifactId>s3</artifactId>
|
||||
<version>${aws-java-sdk-v2.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>software.amazon.awssdk</groupId>
|
||||
<artifactId>url-connection-client</artifactId>
|
||||
<version>${aws.java.sdk.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>commons-io</groupId>
|
||||
@@ -37,9 +43,32 @@
|
||||
<artifactId>commons-codec</artifactId>
|
||||
<version>${commons-codec.version}</version>
|
||||
</dependency>
|
||||
<!-- adobe s3mock -->
|
||||
<dependency>
|
||||
<groupId>com.adobe.testing</groupId>
|
||||
<artifactId>s3mock</artifactId>
|
||||
<version>${com.adobe.testing.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.adobe.testing</groupId>
|
||||
<artifactId>s3mock-testcontainers</artifactId>
|
||||
<version>${com.adobe.testing.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.testcontainers</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
<version>${org.testcontainers.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<aws.java.sdk.version>2.20.52</aws.java.sdk.version>
|
||||
<com.adobe.testing.version>3.3.0</com.adobe.testing.version>
|
||||
<org.testcontainers.version>1.19.4</org.testcontainers.version>
|
||||
<commons-codec.version>1.10.L001</commons-codec.version>
|
||||
<jets3t.version>0.9.4.0014L</jets3t.version>
|
||||
</properties>
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
package com.baeldung.s3;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import software.amazon.awssdk.core.ResponseBytes;
|
||||
import software.amazon.awssdk.core.sync.RequestBody;
|
||||
import software.amazon.awssdk.services.s3.S3Client;
|
||||
import software.amazon.awssdk.services.s3.model.CreateBucketRequest;
|
||||
import software.amazon.awssdk.services.s3.model.DeleteObjectRequest;
|
||||
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
|
||||
import software.amazon.awssdk.services.s3.model.GetObjectResponse;
|
||||
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
|
||||
import software.amazon.awssdk.services.s3.model.S3Exception;
|
||||
|
||||
public class S3CrudService {
|
||||
|
||||
private final S3Client s3Client;
|
||||
|
||||
public S3CrudService(S3Client s3Client) {
|
||||
this.s3Client = s3Client;
|
||||
}
|
||||
|
||||
public void createBucket(String bucketName) {
|
||||
CreateBucketRequest bucketRequest = CreateBucketRequest.builder()
|
||||
.bucket(bucketName)
|
||||
.build();
|
||||
|
||||
s3Client.createBucket(bucketRequest);
|
||||
}
|
||||
|
||||
public void createObject(String bucketName, File inMemoryObject) {
|
||||
PutObjectRequest request = PutObjectRequest.builder()
|
||||
.bucket(bucketName)
|
||||
.key(inMemoryObject.getName())
|
||||
.build();
|
||||
s3Client.putObject(request, RequestBody.fromByteBuffer(inMemoryObject.getContent()));
|
||||
}
|
||||
|
||||
public Optional<byte[]> getObject(String bucketName, String objectKey) {
|
||||
try {
|
||||
GetObjectRequest getObjectRequest = GetObjectRequest.builder()
|
||||
.bucket(bucketName)
|
||||
.key(objectKey)
|
||||
.build();
|
||||
ResponseBytes<GetObjectResponse> responseResponseBytes = s3Client.getObjectAsBytes(getObjectRequest);
|
||||
return Optional.of(responseResponseBytes.asByteArray());
|
||||
} catch (S3Exception e) {
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
public boolean deleteObject(String bucketName, String objectKey) {
|
||||
try {
|
||||
DeleteObjectRequest deleteObjectRequest = DeleteObjectRequest.builder()
|
||||
.bucket(bucketName)
|
||||
.key(objectKey)
|
||||
.build();
|
||||
|
||||
s3Client.deleteObject(deleteObjectRequest);
|
||||
return true;
|
||||
} catch (S3Exception e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package com.baeldung.s3;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static software.amazon.awssdk.http.SdkHttpConfigurationOption.TRUST_ALL_CERTIFICATES;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.Arrays;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.testcontainers.junit.jupiter.Container;
|
||||
import org.testcontainers.junit.jupiter.Testcontainers;
|
||||
|
||||
import com.adobe.testing.s3mock.testcontainers.S3MockContainer;
|
||||
|
||||
import software.amazon.awssdk.http.urlconnection.UrlConnectionHttpClient;
|
||||
import software.amazon.awssdk.services.s3.S3Client;
|
||||
import software.amazon.awssdk.services.s3.S3Configuration;
|
||||
import software.amazon.awssdk.utils.AttributeMap;
|
||||
|
||||
// This live test needs a running Docker instance so that a S3Mock Container can be started
|
||||
|
||||
@Testcontainers
|
||||
public class S3CrudServiceLiveTest {
|
||||
|
||||
private static final String TEST_BUCKET_NAME = "test-bucket";
|
||||
|
||||
@Container
|
||||
private final S3MockContainer s3Mock = new S3MockContainer("latest");
|
||||
private S3Client s3Client;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
var endpoint = s3Mock.getHttpsEndpoint();
|
||||
var serviceConfig = S3Configuration.builder()
|
||||
.pathStyleAccessEnabled(true)
|
||||
.build();
|
||||
var httpClient = UrlConnectionHttpClient.builder()
|
||||
.buildWithDefaults(AttributeMap.builder()
|
||||
.put(TRUST_ALL_CERTIFICATES, Boolean.TRUE)
|
||||
.build());
|
||||
s3Client = S3Client.builder()
|
||||
.endpointOverride(URI.create(endpoint))
|
||||
.serviceConfiguration(serviceConfig)
|
||||
.httpClient(httpClient)
|
||||
.build();
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenVerifyingCreationOfS3Bucket_thenCorrect() {
|
||||
var s3CrudService = new S3CrudService(s3Client);
|
||||
s3CrudService.createBucket(TEST_BUCKET_NAME);
|
||||
|
||||
var createdBucketName = s3Client.listBuckets()
|
||||
.buckets()
|
||||
.get(0)
|
||||
.name();
|
||||
assertThat(TEST_BUCKET_NAME).isEqualTo(createdBucketName);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenCreatingAnObjectOnS3Bucket_thenSameObjectIsRetrived() {
|
||||
var s3CrudService = new S3CrudService(s3Client);
|
||||
s3CrudService.createBucket(TEST_BUCKET_NAME);
|
||||
|
||||
var fileToSave = FileGenerator.generateFiles(1, 100)
|
||||
.get(0);
|
||||
s3CrudService.createObject(TEST_BUCKET_NAME, fileToSave);
|
||||
|
||||
var savedFileContent = s3CrudService.getObject(TEST_BUCKET_NAME, fileToSave.getName());
|
||||
|
||||
assertThat(Arrays.equals(fileToSave.getContent()
|
||||
.array(), savedFileContent.orElse(new byte[] {}))).isTrue();
|
||||
|
||||
s3CrudService.deleteObject(TEST_BUCKET_NAME, fileToSave.getName());
|
||||
|
||||
var deletedFileContent = s3CrudService.getObject(TEST_BUCKET_NAME, fileToSave.getName());
|
||||
assertThat(deletedFileContent).isEmpty();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+95
@@ -0,0 +1,95 @@
|
||||
package com.baeldung.majorityelement;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public class FindMajorityElement {
|
||||
|
||||
public static Integer findMajorityElementUsingForLoop(int[] nums) {
|
||||
int majorityThreshold = nums.length / 2;
|
||||
Integer majorityElement = null;
|
||||
for (int i = 0; i < nums.length; i++) {
|
||||
int count = 0;
|
||||
for (int j = 0; j < nums.length; j++) {
|
||||
if (nums[i] == nums[j]) {
|
||||
count++;
|
||||
}
|
||||
}
|
||||
if (count > majorityThreshold) {
|
||||
return majorityElement = nums[i];
|
||||
}
|
||||
}
|
||||
return majorityElement;
|
||||
}
|
||||
|
||||
public static Integer findMajorityElementUsingSorting(int[] nums) {
|
||||
Arrays.sort(nums);
|
||||
int majorityThreshold = nums.length / 2;
|
||||
int count = 0;
|
||||
for (int i = 0; i < nums.length; i++) {
|
||||
if (nums[i] == nums[majorityThreshold]) {
|
||||
count++;
|
||||
}
|
||||
|
||||
if (count > majorityThreshold) {
|
||||
return nums[majorityThreshold];
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static Integer findMajorityElementUsingHashMap(int[] nums) {
|
||||
Map<Integer, Integer> frequencyMap = new HashMap<>();
|
||||
|
||||
for (int num : nums) {
|
||||
frequencyMap.put(num, frequencyMap.getOrDefault(num, 0) + 1);
|
||||
}
|
||||
|
||||
int majorityThreshold = nums.length / 2;
|
||||
for (Map.Entry<Integer, Integer> entry : frequencyMap.entrySet()) {
|
||||
if (entry.getValue() > majorityThreshold) {
|
||||
return entry.getKey();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static Integer findMajorityElementUsingMooreVoting(int[] nums) {
|
||||
int majorityThreshold = nums.length / 2;
|
||||
int candidate = nums[0];
|
||||
int count = 1;
|
||||
|
||||
for (int i = 1; i < nums.length; i++) {
|
||||
if (count == 0) {
|
||||
candidate = nums[i];
|
||||
count = 1;
|
||||
} else if (candidate == nums[i]) {
|
||||
count++;
|
||||
} else {
|
||||
count--;
|
||||
}
|
||||
|
||||
System.out.println("Iteration " + i + ": [candidate - " + candidate + ", count - " + count + ", element - " + nums[i] + "]");
|
||||
}
|
||||
|
||||
count = 0;
|
||||
for (int num : nums) {
|
||||
if (num == candidate) {
|
||||
count++;
|
||||
}
|
||||
}
|
||||
return count > majorityThreshold ? candidate : null;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
int[] nums = { 2, 3, 2, 4, 2, 5, 2 };
|
||||
Integer majorityElement = findMajorityElementUsingMooreVoting(nums);
|
||||
|
||||
if (majorityElement != null) {
|
||||
System.out.println("Majority element with maximum occurrences: " + majorityElement);
|
||||
} else {
|
||||
System.out.println("No majority element found");
|
||||
}
|
||||
}
|
||||
}
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
package com.baeldung.majorityelement;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class FindMajorityElementUnitTest {
|
||||
|
||||
@Test
|
||||
void givenArrayWithMajorityElement_WhenUsingForLoop_ThenReturnFound() {
|
||||
int[] nums = { 2, 3, 2, 4, 2, 5, 2 };
|
||||
Integer result = FindMajorityElement.findMajorityElementUsingForLoop(nums);
|
||||
assertEquals(2, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenArrayWithoutMajorityElement_WhenUsingForLoop_ThenNotFound() {
|
||||
int[] nums = { 2, 2, 3, 3 };
|
||||
Integer result = FindMajorityElement.findMajorityElementUsingForLoop(nums);
|
||||
assertEquals(null, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArrayWithMajorityElement_WhenUsingSorting_ThenReturnFound() {
|
||||
int[] nums = { 2, 3, 2, 4, 2, 5, 2 };
|
||||
Integer result = FindMajorityElement.findMajorityElementUsingSorting(nums);
|
||||
assertEquals(2, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArrayWithoutMajorityElement_WhenUsingSorting_ThenNotFound() {
|
||||
int[] nums = { 2, 2, 3, 3 };
|
||||
Integer result = FindMajorityElement.findMajorityElementUsingSorting(nums);
|
||||
assertEquals(null, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenArrayWithMajorityElement_WhenUsingHashMap_ThenReturnFound() {
|
||||
int[] nums = { 2, 3, 2, 4, 2, 5, 2 };
|
||||
Integer result = FindMajorityElement.findMajorityElementUsingHashMap(nums);
|
||||
assertEquals(2, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenArrayWithoutMajorityElement_WhenUsingHashMap_ThenNotFound() {
|
||||
int[] nums = { 2, 2, 3, 3 };
|
||||
Integer result = FindMajorityElement.findMajorityElementUsingHashMap(nums);
|
||||
assertEquals(null, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenArrayWithMajorityElement_WhenUsingMooreVoting_ThenReturnFound() {
|
||||
int[] nums = { 2, 3, 2, 4, 2, 5, 2 };
|
||||
Integer result = FindMajorityElement.findMajorityElementUsingMooreVoting(nums);
|
||||
assertEquals(2, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenArrayWithoutMajorityElement_WhenUsingMooreVoting_ThenNotFound() {
|
||||
int[] nums = { 2, 2, 3, 3 };
|
||||
Integer result = FindMajorityElement.findMajorityElementUsingMooreVoting(nums);
|
||||
assertEquals(null, result);
|
||||
}
|
||||
}
|
||||
@@ -4,3 +4,4 @@
|
||||
- [Call a Method on Each Element of a List in Java](https://www.baeldung.com/java-call-method-each-list-item)
|
||||
- [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)
|
||||
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
package com.baeldung.obtainlastsegmentofurl;
|
||||
|
||||
import org.apache.commons.io.FilenameUtils;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.net.URI;
|
||||
import java.net.URISyntaxException;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.fail;
|
||||
|
||||
public class ObtainLastSegmentOfURLUnitTest {
|
||||
@Test
|
||||
public void givenURL_whenUsingURIClass_thenGetLastPathSegment() throws URISyntaxException {
|
||||
URI uri = new URI("https://www.example.com/path/to/resource");
|
||||
String path = uri.getPath();
|
||||
|
||||
String[] segments = path.split("/");
|
||||
String lastSegment = segments[segments.length - 1];
|
||||
|
||||
assertEquals("resource", lastSegment);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenURL_whenUsingPathClass_thenGetLastPathSegment() {
|
||||
String exampleURI = "https://www.example.com/path/to/resource";
|
||||
|
||||
try {
|
||||
URI uri = new URI(exampleURI);
|
||||
String pathString = uri.getPath();
|
||||
Path path = Paths.get(pathString);
|
||||
Path lastSegment = path.getName(path.getNameCount() - 1);
|
||||
|
||||
assertEquals("resource", lastSegment.toString());
|
||||
} catch (Exception e) {
|
||||
fail("Exception occurred: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenURL_whenUsingRegularExpression_thenGetLastPathSegment() throws URISyntaxException {
|
||||
URI uri = new URI("https://www.example.com/path/to/resource");
|
||||
String path = uri.getPath();
|
||||
|
||||
Pattern pattern = Pattern.compile(".*/(.+)");
|
||||
Matcher matcher = pattern.matcher(path);
|
||||
|
||||
if (!matcher.find()) {
|
||||
fail("Regex pattern didn't match.");
|
||||
}
|
||||
|
||||
String lastSegment = matcher.group(1);
|
||||
assertEquals("resource", lastSegment);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenURL_whenUsingFilenameUtilsClass_thenGetLastPathSegment() throws URISyntaxException {
|
||||
String exampleURI = "https://www.example.com/path/to/resource";
|
||||
|
||||
URI uri = new URI(exampleURI);
|
||||
String path = uri.getPath();
|
||||
|
||||
String lastSegment = FilenameUtils.getName(path);
|
||||
|
||||
assertEquals("resource", lastSegment);
|
||||
}
|
||||
}
|
||||
+92
@@ -0,0 +1,92 @@
|
||||
package com.baeldung.blowfish;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.BufferedWriter;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.FileReader;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Base64;
|
||||
|
||||
import javax.crypto.Cipher;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class BlowFishUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenBlowfishAlogrithm_whenEncryptAndDecryptString_thenCompareResults() throws Exception {
|
||||
String secretMessage = "Secret message to encrypt";
|
||||
String secretKey = "MyKey123";
|
||||
byte[] keyData = secretKey.getBytes();
|
||||
|
||||
// Encryption
|
||||
SecretKeySpec secretKeySpec = new SecretKeySpec(keyData, "Blowfish");
|
||||
Cipher encryptCipher = Cipher.getInstance("Blowfish");
|
||||
encryptCipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
|
||||
byte[] encryptedBytes = encryptCipher.doFinal(secretMessage.getBytes(StandardCharsets.UTF_8));
|
||||
String encryptedtext = Base64.getEncoder().encodeToString(encryptedBytes);
|
||||
|
||||
// Decryption
|
||||
byte[] ecryptedtexttobytes = Base64.getDecoder().decode(encryptedtext);
|
||||
Cipher decryptCipher = Cipher.getInstance("Blowfish");
|
||||
decryptCipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
|
||||
byte[] decrypted = decryptCipher.doFinal(ecryptedtexttobytes);
|
||||
String decrypedText = new String(decrypted, StandardCharsets.UTF_8);
|
||||
|
||||
Assertions.assertEquals(secretMessage, decrypedText);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBlowfishAlogrithm_whenEncryptAndDecryptFile_thenCompareResults() throws Exception {
|
||||
String secretKey = "MyKey123";
|
||||
byte[] keyData = secretKey.getBytes();
|
||||
SecretKeySpec secretKeySpec = new SecretKeySpec(keyData, "Blowfish");
|
||||
|
||||
String originalContent = "some secret text file";
|
||||
Path tempFile = Files.createTempFile("temp", "txt");
|
||||
writeFile(tempFile, originalContent);
|
||||
|
||||
// Encryption
|
||||
byte[] fileBytes = Files.readAllBytes(tempFile);
|
||||
Cipher encryptCipher = Cipher.getInstance("Blowfish");
|
||||
encryptCipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
|
||||
byte[] encryptedFileBytes = encryptCipher.doFinal(fileBytes);
|
||||
try (FileOutputStream stream = new FileOutputStream(tempFile.toFile())) {
|
||||
stream.write(encryptedFileBytes);
|
||||
}
|
||||
|
||||
// Decryption
|
||||
encryptedFileBytes = Files.readAllBytes(tempFile);
|
||||
Cipher decryptCipher = Cipher.getInstance("Blowfish");
|
||||
decryptCipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
|
||||
byte[] decryptedFileBytes = decryptCipher.doFinal(encryptedFileBytes);
|
||||
try (FileOutputStream stream = new FileOutputStream(tempFile.toFile())) {
|
||||
stream.write(decryptedFileBytes);
|
||||
}
|
||||
|
||||
String fileContent = readFile(tempFile);
|
||||
|
||||
Assertions.assertEquals(originalContent, fileContent);
|
||||
}
|
||||
|
||||
private void writeFile(Path path, String content) throws Exception {
|
||||
try (BufferedWriter writer = Files.newBufferedWriter(path)) {
|
||||
writer.write(content);
|
||||
}
|
||||
}
|
||||
|
||||
private String readFile(Path path) throws Exception {
|
||||
StringBuilder resultStringBuilder = new StringBuilder();
|
||||
try (BufferedReader br = new BufferedReader(new FileReader(path.toFile()))) {
|
||||
String line;
|
||||
while ((line = br.readLine()) != null) {
|
||||
resultStringBuilder.append(line);
|
||||
}
|
||||
}
|
||||
return resultStringBuilder.toString();
|
||||
}
|
||||
}
|
||||
@@ -50,12 +50,6 @@
|
||||
<version>5.8.1</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.liquibase</groupId>
|
||||
<artifactId>liquibase-core</artifactId>
|
||||
<version>${liquibase.core.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
@@ -84,7 +78,6 @@
|
||||
<apache.tika.version>2.9.1</apache.tika.version>
|
||||
<commons-text.version>1.10.0</commons-text.version>
|
||||
<icu4j.version>74.1</icu4j.version>
|
||||
<liquibase.core.version>4.25.0</liquibase.core.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
@@ -4,3 +4,4 @@
|
||||
- [Check if String is Base64 Encoded](https://www.baeldung.com/java-check-string-base64-encoding)
|
||||
- [Find an Unique Email Address in a List](https://www.baeldung.com/java-find-unique-email-address)
|
||||
- [Get First n Characters in a String in Java](https://www.baeldung.com/get-first-n-characters-in-a-string-in-java)
|
||||
- [Remove Only Trailing Spaces or Whitespace From a String in Java](https://www.baeldung.com/java-string-remove-only-trailing-whitespace)
|
||||
|
||||
+99
@@ -0,0 +1,99 @@
|
||||
package com.baeldung.initials;
|
||||
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.StringTokenizer;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static com.baeldung.initials.InitialFinder.*;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
public class GetInitialsFromNameUnitTest {
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({"John F Kennedy,JFK", ",''", "'',''", "Not Correct 88text,NC", "michael jackson,MJ", "123,''", "123 234A,''", "1test 2test, ''"})
|
||||
public void getInitialFromName_usingLoop(String input, String expected) {
|
||||
String initial = getInitialUsingLoop(input);
|
||||
assertEquals(expected, initial);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({"John F Kennedy,JFK", ",''", "'',''", "Not Correct 88text,NC", "michael jackson,MJ", "123,''", "123 234A,''", "1test 2test, ''"})
|
||||
public void getInitialFromName_usingStringTokenizer(String input, String expected) {
|
||||
String initial = getInitialUsingStringTokenizer(input);
|
||||
assertEquals(expected, initial);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({"John F Kennedy,JFK", ",''", "'',''", "Not Correct 88text,NC", "michael jackson,MJ", "123,''", "123 234A,''", "1test 2test, ''"})
|
||||
public void getInitialFromName_usingRegex(String input, String expected) {
|
||||
String initial = getInitialUsingRegex(input);
|
||||
assertEquals(expected, initial);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({"John F Kennedy,JFK", ",''", "'',''", "Not Correct 88text,NC", "michael jackson,MJ", "123,''", "123 234A,''", "1test 2test, ''"})
|
||||
public void getInitialFromName_usingStreamsAPI(String input, String expected) {
|
||||
String initial = getInitialUsingStreamsAPI(input);
|
||||
assertEquals(expected, initial);
|
||||
}
|
||||
}
|
||||
|
||||
class InitialFinder {
|
||||
public static String getInitialUsingLoop(String name) {
|
||||
if (name == null || name.isEmpty()) {
|
||||
return "";
|
||||
}
|
||||
String[] parts = name.split("\\s+");
|
||||
StringBuilder initials = new StringBuilder();
|
||||
for (String part : parts) {
|
||||
if (part.matches("[a-zA-Z].*")) {
|
||||
initials.append(part.charAt(0));
|
||||
}
|
||||
}
|
||||
return initials.toString().toUpperCase();
|
||||
}
|
||||
|
||||
public static String getInitialUsingStringTokenizer(String name) {
|
||||
if (name == null || name.isEmpty()) {
|
||||
return "";
|
||||
}
|
||||
StringTokenizer tokenizer = new StringTokenizer(name);
|
||||
StringBuilder initials = new StringBuilder();
|
||||
while (tokenizer.hasMoreTokens()) {
|
||||
String part = tokenizer.nextToken();
|
||||
if (part.matches("[a-zA-Z].*")) {
|
||||
initials.append(part.charAt(0));
|
||||
}
|
||||
}
|
||||
return initials.toString().toUpperCase();
|
||||
}
|
||||
|
||||
public static String getInitialUsingRegex(String name) {
|
||||
if (name == null || name.isEmpty()) {
|
||||
return "";
|
||||
}
|
||||
Pattern pattern = Pattern.compile("\\b[a-zA-Z]");
|
||||
Matcher matcher = pattern.matcher(name);
|
||||
StringBuilder initials = new StringBuilder();
|
||||
while (matcher.find()) {
|
||||
initials.append(matcher.group());
|
||||
}
|
||||
return initials.toString().toUpperCase();
|
||||
}
|
||||
|
||||
public static String getInitialUsingStreamsAPI(String name) {
|
||||
if (name == null || name.isEmpty()) {
|
||||
return "";
|
||||
}
|
||||
return Arrays.stream(name.split("\\s+"))
|
||||
.filter(part -> part.matches("[a-zA-Z].*"))
|
||||
.map(part -> part.substring(0, 1))
|
||||
.collect(Collectors.joining())
|
||||
.toUpperCase();
|
||||
}
|
||||
}
|
||||
@@ -5,12 +5,13 @@
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>docker-compose-2</artifactId>
|
||||
<description>Demo project for Spring Boot and Docker - Module docker-compose-2</description>
|
||||
<packaging>pom</packaging>
|
||||
|
||||
<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>
|
||||
|
||||
</project>
|
||||
@@ -8,9 +8,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>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
FROM openjdk:11
|
||||
FROM openjdk:17-jdk-alpine
|
||||
ARG JAR_FILE=target/*.jar
|
||||
COPY ${JAR_FILE} app.jar
|
||||
ENTRYPOINT ["java","-jar","/app.jar"]
|
||||
@@ -1,4 +1,4 @@
|
||||
FROM openjdk:11
|
||||
FROM openjdk:17-jdk-alpine
|
||||
MAINTAINER baeldung.com
|
||||
COPY target/docker-java-jar-0.0.1-SNAPSHOT.jar app.jar
|
||||
ENTRYPOINT ["java","-jar","/app.jar"]
|
||||
|
||||
@@ -7,9 +7,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>
|
||||
|
||||
<build>
|
||||
@@ -29,9 +29,4 @@
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source>11</maven.compiler.source>
|
||||
<maven.compiler.target>11</maven.compiler.target>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
+1
-1
@@ -74,7 +74,7 @@
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<io.grpc.version>1.40.1</io.grpc.version>
|
||||
<io.grpc.version>1.62.2</io.grpc.version>
|
||||
<protoc.version>3.17.2</protoc.version>
|
||||
<os-maven-plugin.version>1.6.2</os-maven-plugin.version>
|
||||
<protobuf-maven-plugin.version>0.6.1</protobuf-maven-plugin.version>
|
||||
|
||||
@@ -1150,7 +1150,7 @@
|
||||
<javassist.version>3.23.1-GA</javassist.version>
|
||||
<!-- The liquibase version should match the one managed by
|
||||
https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-dependencies/${spring-boot.version} -->
|
||||
<liquibase.version>3.6.3</liquibase.version>
|
||||
<liquibase.version>4.9.1</liquibase.version>
|
||||
<liquibase-hibernate5.version>3.6</liquibase-hibernate5.version>
|
||||
<spring.version>5.1.5.RELEASE</spring.version>
|
||||
<validation-api.version>2.0.1.Final</validation-api.version>
|
||||
|
||||
@@ -7,3 +7,4 @@ This module contains articles about Gson
|
||||
- [Difference between Gson @Expose and @SerializedName](https://www.baeldung.com/gson-expose-vs-serializedname)
|
||||
- [Resolving Gson’s “Multiple JSON Fields” Exception](https://www.baeldung.com/java-gson-multiple-json-fields-exception)
|
||||
- [Using Static Methods Instead of Deprecated JsonParser](https://www.baeldung.com/java-static-methods-jsonparser-replacement)
|
||||
- [Gson TypeToken With Dynamic List Item Type](https://www.baeldung.com/gson-typetoken-dynamic-list-item-type)
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user