[BAEL-9712] - Fixed conflicts

This commit is contained in:
amit2103
2018-11-25 00:18:37 +05:30
101 changed files with 3504 additions and 709 deletions
+1 -1
View File
@@ -4,7 +4,7 @@ before_install:
- echo "MAVEN_OPTS='-Xmx2048M -Xss128M -XX:+CMSClassUnloadingEnabled -XX:+UseG1GC -XX:-UseGCOverheadLimit'" > ~/.mavenrc
install: skip
script: travis_wait 60 mvn -q install -Pdefault-first,default-second
script: travis_wait 60 mvn -q install -Pdefault-first,default-second -Dgib.enabled=true
sudo: required
+1
View File
@@ -17,3 +17,4 @@
- [Round Up to the Nearest Hundred](https://www.baeldung.com/java-round-up-nearest-hundred)
- [Calculate Percentage in Java](https://www.baeldung.com/java-calculate-percentage)
- [Converting Between Byte Arrays and Hexadecimal Strings in Java](https://www.baeldung.com/java-byte-arrays-hex-strings)
- [Convert Latitude and Longitude to a 2D Point in Java](https://www.baeldung.com/java-convert-latitude-longitude)
+1
View File
@@ -4,3 +4,4 @@
- [Java 10 LocalVariable Type-Inference](http://www.baeldung.com/java-10-local-variable-type-inference)
- [Guide to Java 10](http://www.baeldung.com/java-10-overview)
- [Copy a List to Another List in Java](http://www.baeldung.com/java-copy-list-to-another)
- [Deep Dive Into the New Java JIT Compiler – Graal](https://www.baeldung.com/graal-java-jit-compiler)
+1
View File
@@ -33,3 +33,4 @@
- [An Overview of Regular Expressions Performance in Java](https://www.baeldung.com/java-regex-performance)
- [Java Primitives versus Objects](https://www.baeldung.com/java-primitives-vs-objects)
- [How to Use if/else Logic in Java 8 Streams](https://www.baeldung.com/java-8-streams-if-else-logic)
- [How to Replace Many if Statements in Java](https://www.baeldung.com/java-replace-if-statements)
@@ -4,11 +4,13 @@ import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.Random;
import java.util.Set;
import java.util.function.Function;
import java.util.function.IntPredicate;
import java.util.function.Predicate;
import java.util.stream.Stream;
import org.apache.commons.lang3.ArrayUtils;
@@ -194,4 +196,16 @@ public class ArrayOperations {
public static <T> T getRandomFromObjectArray(T[] array) {
return array[new Random().nextInt(array.length)];
}
public static Integer[] intersectionSimple(final Integer[] a, final Integer[] b){
return Stream.of(a).filter(Arrays.asList(b)::contains).toArray(Integer[]::new);
}
public static Integer[] intersectionSet(final Integer[] a, final Integer[] b){
return Stream.of(a).filter(Arrays.asList(b)::contains).distinct().toArray(Integer[]::new);
}
public static Integer[] intersectionMultiSet(final Integer[] a, final Integer[] b){
return Stream.of(a).filter(new LinkedList<>(Arrays.asList(b))::remove).toArray(Integer[]::new);
}
}
@@ -0,0 +1,66 @@
package com.baeldung.array.operations;
import org.junit.jupiter.api.Test;
import static com.baeldung.array.operations.ArrayOperations.intersectionMultiSet;
import static com.baeldung.array.operations.ArrayOperations.intersectionSet;
import static com.baeldung.array.operations.ArrayOperations.intersectionSimple;
import static org.assertj.core.api.Assertions.assertThat;
class IntersectionUnitTest {
private static final Integer[] a = { 1, 3, 2 };
private static final Integer[] b = { 4, 3, 2, 4, 2, 3, 4, 4, 3 };
private static final Integer[] c = { 1, 3, 2, 3, 3, 2 };
@Test
void whenIntersectionSimpleIsUsed_thenCommonEntriesAreInTheResult() {
assertThat(intersectionSimple(a, b)).isEqualTo(new Integer[] { 3, 2 });
assertThat(intersectionSimple(b, a)).isEqualTo(new Integer[] { 3, 2, 2, 3, 3 });
}
@Test
void whenIntersectionSimpleIsUsedWithAnArrayAndItself_thenTheResultIsTheIdentity() {
assertThat(intersectionSimple(b, b)).isEqualTo(b);
assertThat(intersectionSimple(a, a)).isEqualTo(a);
}
@Test
void whenIntersectionSetIsUsed_thenCommonEntriesAreInTheResult() {
assertThat(intersectionSet(b, a)).isEqualTo(new Integer[] { 3, 2 });
}
@Test
void whenIntersectionSetIsUsed_thenTheNumberOfEntriesDoesNotChangeWithTheParameterOrder() {
assertThat(intersectionSet(a, b)).isEqualTo(new Integer[] { 3, 2 });
assertThat(intersectionSet(b, a)).isEqualTo(new Integer[] { 3, 2 });
}
@Test
void whenIntersectionSetIsUsedWithAnArrayAndWithItself_andTheInputHasNoDuplicateEntries_ThenTheResultIsTheIdentity() {
assertThat(intersectionSet(a, a)).isEqualTo(a);
}
@Test
void whenIntersectionSetIsUsedWithAnArrayAndWithItself_andTheInputHasDuplicateEntries_ThenTheResultIsNotTheIdentity() {
assertThat(intersectionSet(b, b)).isNotEqualTo(b);
}
@Test
void whenMultiSetIsUsed_thenCommonEntriesAreInTheResult() {
assertThat(intersectionMultiSet(b, a)).isEqualTo(new Integer[] { 3, 2 });
}
@Test
void whenIntersectionMultiSetIsUsed_thenTheNumberOfEntriesDoesNotChangeWithTheParameterOrder() {
assertThat(intersectionMultiSet(a, b)).isEqualTo(new Integer[] { 3, 2 });
assertThat(intersectionMultiSet(b, a)).isEqualTo(new Integer[] { 3, 2 });
assertThat(intersectionMultiSet(b, c)).isEqualTo(new Integer[] { 3, 2, 2, 3, 3 });
assertThat(intersectionMultiSet(c, b)).isEqualTo(new Integer[] { 3, 2, 3, 3, 2 });
}
@Test
void whenIntersectionMultiSetIsUsedWithAnArrayAndWithItself_ThenTheResultIsTheIdentity() {
assertThat(intersectionMultiSet(b, b)).isEqualTo(b);
assertThat(intersectionMultiSet(a, a)).isEqualTo(a);
}
}
+1
View File
@@ -50,3 +50,4 @@
- [Check If Two Lists are Equal in Java](http://www.baeldung.com/java-test-a-list-for-ordinality-and-equality)
- [Java List Initialization in One Line](https://www.baeldung.com/java-init-list-one-line)
- [ClassCastException: Arrays$ArrayList cannot be cast to ArrayList](https://www.baeldung.com/java-classcastexception-arrays-arraylist)
- [A Guide to EnumMap](https://www.baeldung.com/java-enum-map)
+1
View File
@@ -34,3 +34,4 @@
- [Read a File into an ArrayList](https://www.baeldung.com/java-file-to-arraylist)
- [Guide to Java OutputStream](https://www.baeldung.com/java-outputstream)
- [Reading a CSV File into an Array](https://www.baeldung.com/java-csv-file-array)
- [Guide to BufferedReader](https://www.baeldung.com/java-buffered-reader)
+1
View File
@@ -56,4 +56,5 @@
- [How to Separate Double into Integer and Decimal Parts](https://www.baeldung.com/java-separate-double-into-integer-decimal-parts)
- [“Sneaky Throws” in Java](http://www.baeldung.com/java-sneaky-throws)
- [Inheritance and Composition (Is-a vs Has-a relationship) in Java](http://www.baeldung.com/java-inheritance-composition)
- [A Guide to Constructors in Java](https://www.baeldung.com/java-constructors)
@@ -0,0 +1,56 @@
package com.baeldung.constructors;
import java.time.LocalDateTime;
class BankAccount {
String name;
LocalDateTime opened;
double balance;
@Override
public String toString() {
return String.format("%s, %s, %f", this.name, this.opened.toString(), this.balance);
}
public String getName() {
return name;
}
public LocalDateTime getOpened() {
return opened;
}
public double getBalance() {
return this.balance;
}
}
class BankAccountEmptyConstructor extends BankAccount {
public BankAccountEmptyConstructor() {
this.name = "";
this.opened = LocalDateTime.now();
this.balance = 0.0d;
}
}
class BankAccountParameterizedConstructor extends BankAccount {
public BankAccountParameterizedConstructor(String name, LocalDateTime opened, double balance) {
this.name = name;
this.opened = opened;
this.balance = balance;
}
}
class BankAccountCopyConstructor extends BankAccount {
public BankAccountCopyConstructor(String name, LocalDateTime opened, double balance) {
this.name = name;
this.opened = opened;
this.balance = balance;
}
public BankAccountCopyConstructor(BankAccount other) {
this.name = other.name;
this.opened = LocalDateTime.now();
this.balance = 0.0f;
}
}
@@ -0,0 +1,25 @@
package com.baeldung.constructors;
import java.time.LocalDateTime;
class Transaction {
final BankAccountEmptyConstructor bankAccount;
final LocalDateTime date;
final double amount;
public Transaction(BankAccountEmptyConstructor account, LocalDateTime date, double amount) {
this.bankAccount = account;
this.date = date;
this.amount = amount;
}
/*
* Compilation Error :'(, all final variables must be explicitly initialised.
* public Transaction() {
* }
*/
public void invalidMethod() {
// this.amount = 102.03; // Results in a compiler error. You cannot change the value of a final variable.
}
}
@@ -0,0 +1,53 @@
package com.baeldung.constructors;
import com.baeldung.constructors.*;
import java.util.logging.Logger;
import java.time.LocalDateTime;
import java.time.Month;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class ConstructorUnitTest {
final static Logger LOGGER = Logger.getLogger(ConstructorUnitTest.class.getName());
@Test
public void givenNoExplicitContructor_whenUsed_thenFails() {
BankAccount account = new BankAccount();
assertThatThrownBy(() -> { account.toString(); }).isInstanceOf(Exception.class);
}
@Test
public void givenNoArgumentConstructor_whenUsed_thenSucceeds() {
BankAccountEmptyConstructor account = new BankAccountEmptyConstructor();
assertThatCode(() -> {
account.toString();
}).doesNotThrowAnyException();
}
@Test
public void givenParameterisedConstructor_whenUsed_thenSucceeds() {
LocalDateTime opened = LocalDateTime.of(2018, Month.JUNE, 29, 06, 30, 00);
BankAccountParameterizedConstructor account =
new BankAccountParameterizedConstructor("Tom", opened, 1000.0f);
assertThatCode(() -> {
account.toString();
}).doesNotThrowAnyException();
}
@Test
public void givenCopyContructor_whenUser_thenMaintainsLogic() {
LocalDateTime opened = LocalDateTime.of(2018, Month.JUNE, 29, 06, 30, 00);
BankAccountCopyConstructor account = new BankAccountCopyConstructor("Tim", opened, 1000.0f);
BankAccountCopyConstructor newAccount = new BankAccountCopyConstructor(account);
assertThat(account.getName()).isEqualTo(newAccount.getName());
assertThat(account.getOpened()).isNotEqualTo(newAccount.getOpened());
assertThat(newAccount.getBalance()).isEqualTo(0.0f);
}
}
+3
View File
@@ -85,3 +85,6 @@
- [A Guide to SimpleDateFormat](https://www.baeldung.com/java-simple-date-format)
- [SSL Handshake Failures](https://www.baeldung.com/java-ssl-handshake-failures)
- [Implementing a Binary Tree in Java](https://www.baeldung.com/java-binary-tree)
- [Changing the Order in a Sum Operation Can Produce Different Results?](https://www.baeldung.com/java-floating-point-sum-order)
- [Java – Try with Resources](https://www.baeldung.com/java-try-with-resources)
- [Abstract Classes in Java](https://www.baeldung.com/java-abstract-class)
@@ -0,0 +1,9 @@
package com.baeldung.className;
public class RetrievingClassName {
public class InnerClass {
}
}
@@ -0,0 +1,156 @@
package com.baeldung.className;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
public class RetrievingClassNameUnitTest {
// Retrieving Simple Name
@Test
public void givenRetrievingClassName_whenGetSimpleName_thenRetrievingClassName() {
assertEquals("RetrievingClassName", RetrievingClassName.class.getSimpleName());
}
@Test
public void givenPrimitiveInt_whenGetSimpleName_thenInt() {
assertEquals("int", int.class.getSimpleName());
}
@Test
public void givenRetrievingClassNameArray_whenGetSimpleName_thenRetrievingClassNameWithBrackets() {
assertEquals("RetrievingClassName[]", RetrievingClassName[].class.getSimpleName());
assertEquals("RetrievingClassName[][]", RetrievingClassName[][].class.getSimpleName());
}
@Test
public void givenAnonymousClass_whenGetSimpleName_thenEmptyString() {
assertEquals("", new RetrievingClassName() {}.getClass().getSimpleName());
}
// Retrieving Other Names
// - Primitive Types
@Test
public void givenPrimitiveInt_whenGetName_thenInt() {
assertEquals("int", int.class.getName());
}
@Test
public void givenPrimitiveInt_whenGetTypeName_thenInt() {
assertEquals("int", int.class.getTypeName());
}
@Test
public void givenPrimitiveInt_whenGetCanonicalName_thenInt() {
assertEquals("int", int.class.getCanonicalName());
}
// - Object Types
@Test
public void givenRetrievingClassName_whenGetName_thenCanonicalName() {
assertEquals("com.baeldung.className.RetrievingClassName", RetrievingClassName.class.getName());
}
@Test
public void givenRetrievingClassName_whenGetTypeName_thenCanonicalName() {
assertEquals("com.baeldung.className.RetrievingClassName", RetrievingClassName.class.getTypeName());
}
@Test
public void givenRetrievingClassName_whenGetCanonicalName_thenCanonicalName() {
assertEquals("com.baeldung.className.RetrievingClassName", RetrievingClassName.class.getCanonicalName());
}
// - Inner Classes
@Test
public void givenRetrievingClassNameInnerClass_whenGetName_thenCanonicalNameWithDollarSeparator() {
assertEquals("com.baeldung.className.RetrievingClassName$InnerClass", RetrievingClassName.InnerClass.class.getName());
}
@Test
public void givenRetrievingClassNameInnerClass_whenGetTypeName_thenCanonicalNameWithDollarSeparator() {
assertEquals("com.baeldung.className.RetrievingClassName$InnerClass", RetrievingClassName.InnerClass.class.getTypeName());
}
@Test
public void givenRetrievingClassNameInnerClass_whenGetCanonicalName_thenCanonicalName() {
assertEquals("com.baeldung.className.RetrievingClassName.InnerClass", RetrievingClassName.InnerClass.class.getCanonicalName());
}
// - Anonymous Classes
@Test
public void givenAnonymousClass_whenGetName_thenCallingClassCanonicalNameWithDollarSeparatorAndCountNumber() {
// These are the second and third appearences of an anonymous class in RetrievingClassNameUnitTest, hence $2 and $3 expectations
assertEquals("com.baeldung.className.RetrievingClassNameUnitTest$2", new RetrievingClassName() {}.getClass().getName());
assertEquals("com.baeldung.className.RetrievingClassNameUnitTest$3", new RetrievingClassName() {}.getClass().getName());
}
@Test
public void givenAnonymousClass_whenGetTypeName_thenCallingClassCanonicalNameWithDollarSeparatorAndCountNumber() {
// These are the fourth and fifth appearences of an anonymous class in RetrievingClassNameUnitTest, hence $4 and $5 expectations
assertEquals("com.baeldung.className.RetrievingClassNameUnitTest$4", new RetrievingClassName() {}.getClass().getTypeName());
assertEquals("com.baeldung.className.RetrievingClassNameUnitTest$5", new RetrievingClassName() {}.getClass().getTypeName());
}
@Test
public void givenAnonymousClass_whenGetCanonicalName_thenNull() {
assertNull(new RetrievingClassName() {}.getClass().getCanonicalName());
}
// - Arrays
@Test
public void givenPrimitiveIntArray_whenGetName_thenOpeningBracketsAndPrimitiveIntLetter() {
assertEquals("[I", int[].class.getName());
assertEquals("[[I", int[][].class.getName());
}
@Test
public void givenRetrievingClassNameArray_whenGetName_thenOpeningBracketsLetterLAndRetrievingClassNameGetName() {
assertEquals("[Lcom.baeldung.className.RetrievingClassName;", RetrievingClassName[].class.getName());
assertEquals("[[Lcom.baeldung.className.RetrievingClassName;", RetrievingClassName[][].class.getName());
}
@Test
public void givenRetrievingClassNameInnerClassArray_whenGetName_thenOpeningBracketsLetterLAndRetrievingClassNameInnerClassGetName() {
assertEquals("[Lcom.baeldung.className.RetrievingClassName$InnerClass;", RetrievingClassName.InnerClass[].class.getName());
assertEquals("[[Lcom.baeldung.className.RetrievingClassName$InnerClass;", RetrievingClassName.InnerClass[][].class.getName());
}
@Test
public void givenPrimitiveIntArray_whenGetTypeName_thenPrimitiveIntGetTypeNameWithBrackets() {
assertEquals("int[]", int[].class.getTypeName());
assertEquals("int[][]", int[][].class.getTypeName());
}
@Test
public void givenRetrievingClassNameArray_whenGetTypeName_thenRetrievingClassNameGetTypeNameWithBrackets() {
assertEquals("com.baeldung.className.RetrievingClassName[]", RetrievingClassName[].class.getTypeName());
assertEquals("com.baeldung.className.RetrievingClassName[][]", RetrievingClassName[][].class.getTypeName());
}
@Test
public void givenRetrievingClassNameInnerClassArray_whenGetTypeName_thenRetrievingClassNameInnerClassGetTypeNameWithBrackets() {
assertEquals("com.baeldung.className.RetrievingClassName$InnerClass[]", RetrievingClassName.InnerClass[].class.getTypeName());
assertEquals("com.baeldung.className.RetrievingClassName$InnerClass[][]", RetrievingClassName.InnerClass[][].class.getTypeName());
}
@Test
public void givenPrimitiveIntArray_whenGetCanonicalName_thenPrimitiveIntGetCanonicalNameWithBrackets() {
assertEquals("int[]", int[].class.getCanonicalName());
assertEquals("int[][]", int[][].class.getCanonicalName());
}
@Test
public void givenRetrievingClassNameArray_whenGetCanonicalName_thenRetrievingClassNameGetCanonicalNameWithBrackets() {
assertEquals("com.baeldung.className.RetrievingClassName[]", RetrievingClassName[].class.getCanonicalName());
assertEquals("com.baeldung.className.RetrievingClassName[][]", RetrievingClassName[][].class.getCanonicalName());
}
@Test
public void givenRetrievingClassNameInnerClassArray_whenGetCanonicalName_thenRetrievingClassNameInnerClassGetCanonicalNameWithBrackets() {
assertEquals("com.baeldung.className.RetrievingClassName.InnerClass[]", RetrievingClassName.InnerClass[].class.getCanonicalName());
assertEquals("com.baeldung.className.RetrievingClassName.InnerClass[][]", RetrievingClassName.InnerClass[][].class.getCanonicalName());
}
}
@@ -0,0 +1,83 @@
package com.baeldung.string;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class StringReplaceAndRemoveUnitTest {
@Test
public void givenTestStrings_whenReplace_thenProcessedString() {
String master = "Hello World Baeldung!";
String target = "Baeldung";
String replacement = "Java";
String processed = master.replace(target, replacement);
assertTrue(processed.contains(replacement));
assertFalse(processed.contains(target));
}
@Test
public void givenTestStrings_whenReplaceAll_thenProcessedString() {
String master2 = "Welcome to Baeldung, Hello World Baeldung";
String regexTarget= "(Baeldung)$";
String replacement = "Java";
String processed2 = master2.replaceAll(regexTarget, replacement);
assertTrue(processed2.endsWith("Java"));
}
@Test
public void givenTestStrings_whenStringBuilderMethods_thenProcessedString() {
String master = "Hello World Baeldung!";
String target = "Baeldung";
String replacement = "Java";
int startIndex = master.indexOf(target);
int stopIndex = startIndex + target.length();
StringBuilder builder = new StringBuilder(master);
builder.delete(startIndex, stopIndex);
assertFalse(builder.toString().contains(target));
builder.replace(startIndex, stopIndex, replacement);
assertTrue(builder.toString().contains(replacement));
}
@Test
public void givenTestStrings_whenStringUtilsMethods_thenProcessedStrings() {
String master = "Hello World Baeldung!";
String target = "Baeldung";
String replacement = "Java";
String processed = StringUtils.replace(master, target, replacement);
assertTrue(processed.contains(replacement));
String master2 = "Hello World Baeldung!";
String target2 = "baeldung";
String processed2 = StringUtils.replaceIgnoreCase(master2, target2, replacement);
assertFalse(processed2.contains(target));
}
}
+3 -4
View File
@@ -71,9 +71,8 @@
</build>
<properties>
<io.grpc.version>1.5.0</io.grpc.version>
<os-maven-plugin.version>1.5.0.Final</os-maven-plugin.version>
<protobuf-maven-plugin.version>0.5.0</protobuf-maven-plugin.version>
<io.grpc.version>1.16.1</io.grpc.version>
<os-maven-plugin.version>1.6.1</os-maven-plugin.version>
<protobuf-maven-plugin.version>0.6.1</protobuf-maven-plugin.version>
</properties>
</project>
@@ -10,7 +10,7 @@ import io.grpc.ManagedChannelBuilder;
public class GrpcClient {
public static void main(String[] args) throws InterruptedException {
ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 8080)
.usePlaintext(true)
.usePlaintext()
.build();
HelloServiceGrpc.HelloServiceBlockingStub stub
+1
View File
@@ -24,3 +24,4 @@
- [Add Hours To a Date In Java](http://www.baeldung.com/java-add-hours-date)
- [Guide to DateTimeFormatter](https://www.baeldung.com/java-datetimeformatter)
- [Format ZonedDateTime to String](https://www.baeldung.com/java-format-zoned-datetime-string)
- [Convert Between java.time.Instant and java.sql.Timestamp](Convert Between java.time.Instant and java.sql.Timestamp)
@@ -0,0 +1,22 @@
package com.baeldung.timestamp;
import org.junit.Assert;
import org.junit.Test;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class StringToTimestampConverterUnitTest {
@Test
public void givenDatePattern_whenParsing_thenTimestampIsCorrect() {
String pattern = "MMM dd, yyyy HH:mm:ss.SSSSSSSS";
String timestampAsString = "Nov 12, 2018 13:02:56.12345678";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
LocalDateTime localDateTime = LocalDateTime.from(formatter.parse(timestampAsString));
Timestamp timestamp = Timestamp.valueOf(localDateTime);
Assert.assertEquals("2018-11-12 13:02:56.12345678", timestamp.toString());
}
}
@@ -0,0 +1,19 @@
package com.baeldung.timestamp;
import org.junit.Assert;
import org.junit.jupiter.api.Test;
import java.sql.Timestamp;
import java.time.format.DateTimeFormatter;
public class TimestampToStringConverterTest {
@Test
public void givenDatePattern_whenFormatting_thenResultingStringIsCorrect() {
Timestamp timestamp = Timestamp.valueOf("2018-12-12 01:02:03.123456789");
DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
String timestampAsString = formatter.format(timestamp.toLocalDateTime());
Assert.assertEquals("2018-12-12T01:02:03.123456789", timestampAsString);
}
}
+1
View File
@@ -36,3 +36,4 @@
- [String Performance Hints](https://www.baeldung.com/java-string-performance)
- [Using indexOf to Find All Occurrences of a Word in a String](https://www.baeldung.com/java-indexOf-find-string-occurrences)
- [Java Base64 Encoding and Decoding](https://www.baeldung.com/java-base64-encode-and-decode)
- [Generate a Secure Random Password in Java](https://www.baeldung.com/java-generate-secure-password)
@@ -0,0 +1,102 @@
package com.baeldung.stringduplicates;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;
public class RemoveDuplicateFromString {
String removeDuplicatesUsingCharArray(String str) {
char[] chars = str.toCharArray();
StringBuilder sb = new StringBuilder();
int repeatedCtr;
for (int i = 0; i < chars.length; i++) {
repeatedCtr = 0;
for (int j = i + 1; j < chars.length; j++) {
if (chars[i] == chars[j]) {
repeatedCtr++;
}
}
if (repeatedCtr == 0) {
sb.append(chars[i]);
}
}
return sb.toString();
}
String removeDuplicatesUsinglinkedHashSet(String str) {
StringBuilder sb = new StringBuilder();
Set<Character> linkedHashSet = new LinkedHashSet<>();
for (int i = 0; i < str.length(); i++) {
linkedHashSet.add(str.charAt(i));
}
for (Character c : linkedHashSet) {
sb.append(c);
}
return sb.toString();
}
String removeDuplicatesUsingSorting(String str) {
StringBuilder sb = new StringBuilder();
if(!str.isEmpty()) {
char[] chars = str.toCharArray();
Arrays.sort(chars);
sb.append(chars[0]);
for (int i = 1; i < chars.length; i++) {
if (chars[i] != chars[i - 1]) {
sb.append(chars[i]);
}
}
}
return sb.toString();
}
String removeDuplicatesUsingHashSet(String str) {
StringBuilder sb = new StringBuilder();
Set<Character> hashSet = new HashSet<>();
for (int i = 0; i < str.length(); i++) {
hashSet.add(str.charAt(i));
}
for (Character c : hashSet) {
sb.append(c);
}
return sb.toString();
}
String removeDuplicatesUsingIndexOf(String str) {
StringBuilder sb = new StringBuilder();
int idx;
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
idx = str.indexOf(c, i + 1);
if (idx == -1) {
sb.append(c);
}
}
return sb.toString();
}
String removeDuplicatesUsingDistinct(String str) {
StringBuilder sb = new StringBuilder();
str.chars().distinct().forEach(c -> sb.append((char) c));
return sb.toString();
}
}
@@ -0,0 +1,83 @@
package com.baeldung.string;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class StringReplaceAndRemoveUnitTest {
@Test
public void givenTestStrings_whenReplace_thenProcessedString() {
String master = "Hello World Baeldung!";
String target = "Baeldung";
String replacement = "Java";
String processed = master.replace(target, replacement);
assertTrue(processed.contains(replacement));
assertFalse(processed.contains(target));
}
@Test
public void givenTestStrings_whenReplaceAll_thenProcessedString() {
String master2 = "Welcome to Baeldung, Hello World Baeldung";
String regexTarget= "(Baeldung)$";
String replacement = "Java";
String processed2 = master2.replaceAll(regexTarget, replacement);
assertTrue(processed2.endsWith("Java"));
}
@Test
public void givenTestStrings_whenStringBuilderMethods_thenProcessedString() {
String master = "Hello World Baeldung!";
String target = "Baeldung";
String replacement = "Java";
int startIndex = master.indexOf(target);
int stopIndex = startIndex + target.length();
StringBuilder builder = new StringBuilder(master);
builder.delete(startIndex, stopIndex);
assertFalse(builder.toString().contains(target));
builder.replace(startIndex, stopIndex, replacement);
assertTrue(builder.toString().contains(replacement));
}
@Test
public void givenTestStrings_whenStringUtilsMethods_thenProcessedStrings() {
String master = "Hello World Baeldung!";
String target = "Baeldung";
String replacement = "Java";
String processed = StringUtils.replace(master, target, replacement);
assertTrue(processed.contains(replacement));
String master2 = "Hello World Baeldung!";
String target2 = "baeldung";
String processed2 = StringUtils.replaceIgnoreCase(master2, target2, replacement);
assertFalse(processed2.contains(target));
}
}
@@ -0,0 +1,82 @@
package com.baeldung.stringduplicates;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class RemoveDuplicateFromStringUnitTest {
private final static String STR1 = "racecar";
private final static String STR2 = "J2ee programming";
private final static String STR_EMPTY = "";
private RemoveDuplicateFromString removeDuplicateFromString;
@Before
public void executedBeforeEach() {
removeDuplicateFromString = new RemoveDuplicateFromString();
}
@Test
public void whenUsingCharArray_DuplicatesShouldBeRemovedWithoutKeepingStringOrder() {
String str1 = removeDuplicateFromString.removeDuplicatesUsingCharArray(STR1);
String str2 = removeDuplicateFromString.removeDuplicatesUsingCharArray(STR2);
String strEmpty = removeDuplicateFromString.removeDuplicatesUsingCharArray(STR_EMPTY);
Assert.assertEquals("", strEmpty);
Assert.assertEquals("ecar", str1);
Assert.assertEquals("J2e poraming", str2);
}
@Test
public void whenUsingLinkedHashSet_DuplicatesShouldBeRemovedAndItKeepStringOrder() {
String str1 = removeDuplicateFromString.removeDuplicatesUsinglinkedHashSet(STR1);
String str2 = removeDuplicateFromString.removeDuplicatesUsinglinkedHashSet(STR2);
String strEmpty = removeDuplicateFromString.removeDuplicatesUsinglinkedHashSet(STR_EMPTY);
Assert.assertEquals("", strEmpty);
Assert.assertEquals("race", str1);
Assert.assertEquals("J2e progamin", str2);
}
@Test
public void whenUsingSorting_DuplicatesShouldBeRemovedWithoutKeepingStringOrder() {
String str1 = removeDuplicateFromString.removeDuplicatesUsingSorting(STR1);
String str2 = removeDuplicateFromString.removeDuplicatesUsingSorting(STR2);
String strEmpty = removeDuplicateFromString.removeDuplicatesUsingSorting(STR_EMPTY);
Assert.assertEquals("", strEmpty);
Assert.assertEquals("acer", str1);
Assert.assertEquals(" 2Jaegimnopr", str2);
}
@Test
public void whenUsingHashSet_DuplicatesShouldBeRemovedWithoutKeepingStringOrder() {
String str1 = removeDuplicateFromString.removeDuplicatesUsingHashSet(STR1);
String str2 = removeDuplicateFromString.removeDuplicatesUsingHashSet(STR2);
String strEmpty = removeDuplicateFromString.removeDuplicatesUsingHashSet(STR_EMPTY);
Assert.assertEquals("", strEmpty);
Assert.assertEquals("arce", str1);
Assert.assertEquals(" pa2regiJmno", str2);
}
@Test
public void whenUsingIndexOf_DuplicatesShouldBeRemovedWithoutKeepingStringOrder() {
String str1 = removeDuplicateFromString.removeDuplicatesUsingIndexOf(STR1);
String str2 = removeDuplicateFromString.removeDuplicatesUsingIndexOf(STR2);
String strEmpty = removeDuplicateFromString.removeDuplicatesUsingIndexOf(STR_EMPTY);
Assert.assertEquals("", strEmpty);
Assert.assertEquals("ecar", str1);
Assert.assertEquals("J2e poraming", str2);
}
@Test
public void whenUsingJava8_DuplicatesShouldBeRemovedAndItKeepStringOrder() {
String str1 = removeDuplicateFromString.removeDuplicatesUsingDistinct(STR1);
String str2 = removeDuplicateFromString.removeDuplicatesUsingDistinct(STR2);
String strEmpty = removeDuplicateFromString.removeDuplicatesUsingDistinct(STR_EMPTY);
Assert.assertEquals("", strEmpty);
Assert.assertEquals("race", str1);
Assert.assertEquals("J2e progamin", str2);
}
}
+7
View File
@@ -87,6 +87,13 @@
<artifactId>h2</artifactId>
<version>${h2database.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.arrow-kt/arrow-core -->
<dependency>
<groupId>io.arrow-kt</groupId>
<artifactId>arrow-core</artifactId>
<version>0.7.3</version>
</dependency>
</dependencies>
<properties>
@@ -0,0 +1,54 @@
package com.baeldung.kotlin.arrow
import arrow.core.Either
import arrow.core.filterOrElse
import kotlin.math.sqrt
class FunctionalErrorHandlingWithEither {
sealed class ComputeProblem {
object OddNumber : ComputeProblem()
object NotANumber : ComputeProblem()
}
fun parseInput(s : String) : Either<ComputeProblem, Int> = Either.cond(s.toIntOrNull() != null, {-> s.toInt()}, {->ComputeProblem.NotANumber} )
fun isEven(x : Int) : Boolean = x % 2 == 0
fun biggestDivisor(x: Int) : Int = biggestDivisor(x, 2)
fun biggestDivisor(x : Int, y : Int) : Int {
if(x == y){
return 1;
}
if(x % y == 0){
return x / y;
}
return biggestDivisor(x, y+1)
}
fun isSquareNumber(x : Int) : Boolean {
val sqrt: Double = sqrt(x.toDouble())
return sqrt % 1.0 == 0.0
}
fun computeWithEither(input : String) : Either<ComputeProblem, Boolean> {
return parseInput(input)
.filterOrElse(::isEven) {->ComputeProblem.OddNumber}
.map (::biggestDivisor)
.map (::isSquareNumber)
}
fun computeWithEitherClient(input : String) {
val computeWithEither = computeWithEither(input)
when(computeWithEither){
is Either.Right -> "The greatest divisor is square number: ${computeWithEither.b}"
is Either.Left -> when(computeWithEither.a){
is ComputeProblem.NotANumber -> "Wrong input! Not a number!"
is ComputeProblem.OddNumber -> "It is an odd number!"
}
}
}
}
@@ -0,0 +1,46 @@
package com.baeldung.kotlin.arrow
import arrow.core.None
import arrow.core.Option
import arrow.core.Some
import kotlin.math.sqrt
class FunctionalErrorHandlingWithOption {
fun parseInput(s : String) : Option<Int> = Option.fromNullable(s.toIntOrNull())
fun isEven(x : Int) : Boolean = x % 2 == 0
fun biggestDivisor(x: Int) : Int = biggestDivisor(x, 2)
fun biggestDivisor(x : Int, y : Int) : Int {
if(x == y){
return 1;
}
if(x % y == 0){
return x / y;
}
return biggestDivisor(x, y+1)
}
fun isSquareNumber(x : Int) : Boolean {
val sqrt: Double = sqrt(x.toDouble())
return sqrt % 1.0 == 0.0
}
fun computeWithOption(input : String) : Option<Boolean> {
return parseInput(input)
.filter(::isEven)
.map(::biggestDivisor)
.map(::isSquareNumber)
}
fun computeWithOptionClient(input : String) : String{
val computeOption = computeWithOption(input)
return when(computeOption){
is None -> "Not an even number!"
is Some -> "The greatest divisor is square number: ${computeOption.t}"
}
}
}
@@ -0,0 +1,143 @@
package com.baeldung.kotlin.arrow
import arrow.core.*
import org.junit.Assert
import org.junit.Test
class FunctionalDataTypes {
@Test
fun whenIdCreated_thanValueIsPresent(){
val id = Id("foo")
val justId = Id.just("foo");
Assert.assertEquals("foo", id.extract())
Assert.assertEquals(justId, id)
}
fun length(s : String) : Int = s.length
fun isBigEnough(i : Int) : Boolean = i > 10
@Test
fun whenIdCreated_thanMapIsAssociative(){
val foo = Id("foo")
val map1 = foo.map(::length)
.map(::isBigEnough)
val map2 = foo.map { s -> isBigEnough(length(s)) }
Assert.assertEquals(map1, map2)
}
fun lengthId(s : String) : Id<Int> = Id.just(length(s))
fun isBigEnoughId(i : Int) : Id<Boolean> = Id.just(isBigEnough(i))
@Test
fun whenIdCreated_thanFlatMapIsAssociative(){
val bar = Id("bar")
val flatMap = bar.flatMap(::lengthId)
.flatMap(::isBigEnoughId)
val flatMap1 = bar.flatMap { s -> lengthId(s).flatMap(::isBigEnoughId) }
Assert.assertEquals(flatMap, flatMap1)
}
@Test
fun whenOptionCreated_thanValueIsPresent(){
val factory = Option.just(42)
val constructor = Option(42)
val emptyOptional = Option.empty<Integer>()
val fromNullable = Option.fromNullable(null)
Assert.assertEquals(42, factory.getOrElse { -1 })
Assert.assertEquals(factory, constructor)
Assert.assertEquals(emptyOptional, fromNullable)
}
@Test
fun whenOptionCreated_thanConstructorDifferFromFactory(){
val constructor : Option<String?> = Option(null)
val fromNullable : Option<String?> = Option.fromNullable(null)
try{
constructor.map { s -> s!!.length }
Assert.fail()
} catch (e : KotlinNullPointerException){
fromNullable.map { s->s!!.length }
}
Assert.assertNotEquals(constructor, fromNullable)
}
fun wrapper(x : Integer?) : Option<Int> = if (x == null) Option.just(-1) else Option.just(x.toInt())
@Test
fun whenOptionFromNullableCreated_thanItBreaksLeftIdentity(){
val optionFromNull = Option.fromNullable(null)
Assert.assertNotEquals(optionFromNull.flatMap(::wrapper), wrapper(null))
}
@Test
fun whenEitherCreated_thanOneValueIsPresent(){
val rightOnly : Either<String,Int> = Either.right(42)
val leftOnly : Either<String,Int> = Either.left("foo")
Assert.assertTrue(rightOnly.isRight())
Assert.assertTrue(leftOnly.isLeft())
Assert.assertEquals(42, rightOnly.getOrElse { -1 })
Assert.assertEquals(-1, leftOnly.getOrElse { -1 })
Assert.assertEquals(0, rightOnly.map { it % 2 }.getOrElse { -1 })
Assert.assertEquals(-1, leftOnly.map { it % 2 }.getOrElse { -1 })
Assert.assertTrue(rightOnly.flatMap { Either.Right(it % 2) }.isRight())
Assert.assertTrue(leftOnly.flatMap { Either.Right(it % 2) }.isLeft())
}
@Test
fun whenEvalNowUsed_thenMapEvaluatedLazily(){
val now = Eval.now(1)
Assert.assertEquals(1, now.value())
var counter : Int = 0
val map = now.map { x -> counter++; x+1 }
Assert.assertEquals(0, counter)
val value = map.value()
Assert.assertEquals(2, value)
Assert.assertEquals(1, counter)
}
@Test
fun whenEvalLaterUsed_theResultIsMemoized(){
var counter : Int = 0
val later = Eval.later { counter++; counter }
Assert.assertEquals(0, counter)
val firstValue = later.value()
Assert.assertEquals(1, firstValue)
Assert.assertEquals(1, counter)
val secondValue = later.value()
Assert.assertEquals(1, secondValue)
Assert.assertEquals(1, counter)
}
@Test
fun whenEvalAlwaysUsed_theResultIsNotMemoized(){
var counter : Int = 0
val later = Eval.always { counter++; counter }
Assert.assertEquals(0, counter)
val firstValue = later.value()
Assert.assertEquals(1, firstValue)
Assert.assertEquals(1, counter)
val secondValue = later.value()
Assert.assertEquals(2, secondValue)
Assert.assertEquals(2, counter)
}
}
@@ -0,0 +1,68 @@
package com.baeldung.kotlin.arrow
import arrow.core.Either
import com.baeldung.kotlin.arrow.FunctionalErrorHandlingWithEither.ComputeProblem.NotANumber
import com.baeldung.kotlin.arrow.FunctionalErrorHandlingWithEither.ComputeProblem.OddNumber
import org.junit.Assert
import org.junit.Test
class FunctionalErrorHandlingWithEitherTest {
val operator = FunctionalErrorHandlingWithEither()
@Test
fun givenInvalidInput_whenComputeInvoked_NotANumberIsPresent(){
val computeWithEither = operator.computeWithEither("bar")
Assert.assertTrue(computeWithEither.isLeft())
when(computeWithEither){
is Either.Left -> when(computeWithEither.a){
NotANumber -> "Ok."
else -> Assert.fail()
}
else -> Assert.fail()
}
}
@Test
fun givenOddNumberInput_whenComputeInvoked_OddNumberIsPresent(){
val computeWithEither = operator.computeWithEither("121")
Assert.assertTrue(computeWithEither.isLeft())
when(computeWithEither){
is Either.Left -> when(computeWithEither.a){
OddNumber -> "Ok."
else -> Assert.fail()
}
else -> Assert.fail()
}
}
@Test
fun givenEvenNumberWithoutSquare_whenComputeInvoked_OddNumberIsPresent(){
val computeWithEither = operator.computeWithEither("100")
Assert.assertTrue(computeWithEither.isRight())
when(computeWithEither){
is Either.Right -> when(computeWithEither.b){
false -> "Ok."
else -> Assert.fail()
}
else -> Assert.fail()
}
}
@Test
fun givenEvenNumberWithSquare_whenComputeInvoked_OddNumberIsPresent(){
val computeWithEither = operator.computeWithEither("98")
Assert.assertTrue(computeWithEither.isRight())
when(computeWithEither){
is Either.Right -> when(computeWithEither.b){
true -> "Ok."
else -> Assert.fail()
}
else -> Assert.fail()
}
}
}

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