Merge branch 'master' into master
This commit is contained in:
+19
@@ -0,0 +1,19 @@
|
||||
package com.baeldung.random;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
|
||||
public class LegacyRandomDateTimes {
|
||||
|
||||
public static Date between(Date startInclusive, Date endExclusive) {
|
||||
long startMillis = startInclusive.getTime();
|
||||
long endMillis = endExclusive.getTime();
|
||||
long randomMillisSinceEpoch = ThreadLocalRandom.current().nextLong(startMillis, endMillis);
|
||||
|
||||
return new Date(randomMillisSinceEpoch);
|
||||
}
|
||||
|
||||
public static Date timestamp() {
|
||||
return new Date(ThreadLocalRandom.current().nextInt() * 1000L);
|
||||
}
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
package com.baeldung.random;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
|
||||
public class RandomDateTimes {
|
||||
|
||||
public static Instant timestamp() {
|
||||
return Instant.ofEpochSecond(ThreadLocalRandom.current().nextInt());
|
||||
}
|
||||
|
||||
public static Instant between(Instant startInclusive, Instant endExclusive) {
|
||||
long startSeconds = startInclusive.getEpochSecond();
|
||||
long endSeconds = endExclusive.getEpochSecond();
|
||||
long random = ThreadLocalRandom.current().nextLong(startSeconds, endSeconds);
|
||||
|
||||
return Instant.ofEpochSecond(random);
|
||||
}
|
||||
|
||||
public static Instant after(Instant startInclusive) {
|
||||
return between(startInclusive, Instant.MAX);
|
||||
}
|
||||
|
||||
public static Instant before(Instant upperExclusive) {
|
||||
return between(Instant.MIN, upperExclusive);
|
||||
}
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
package com.baeldung.random;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
|
||||
public class RandomDates {
|
||||
|
||||
public static LocalDate between(LocalDate startInclusive, LocalDate endExclusive) {
|
||||
long startEpochDay = startInclusive.toEpochDay();
|
||||
long endEpochDay = endExclusive.toEpochDay();
|
||||
long randomDay = ThreadLocalRandom.current().nextLong(startEpochDay, endEpochDay);
|
||||
|
||||
return LocalDate.ofEpochDay(randomDay);
|
||||
}
|
||||
|
||||
public static LocalDate date() {
|
||||
int hundredYears = 100 * 365;
|
||||
return LocalDate.ofEpochDay(ThreadLocalRandom.current().nextInt(-hundredYears, hundredYears));
|
||||
}
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package com.baeldung.random;
|
||||
|
||||
import java.time.LocalTime;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
|
||||
public class RandomTimes {
|
||||
|
||||
public static LocalTime between(LocalTime startTime, LocalTime endTime) {
|
||||
int startSeconds = startTime.toSecondOfDay();
|
||||
int endSeconds = endTime.toSecondOfDay();
|
||||
int randomTime = ThreadLocalRandom.current().nextInt(startSeconds, endSeconds);
|
||||
|
||||
return LocalTime.ofSecondOfDay(randomTime);
|
||||
}
|
||||
|
||||
public static LocalTime time() {
|
||||
return between(LocalTime.MIN, LocalTime.MAX);
|
||||
}
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
package com.baeldung.random;
|
||||
|
||||
import org.junit.jupiter.api.RepeatedTest;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
class LegacyRandomDateTimesUnitTest {
|
||||
|
||||
private static final Date MIN_DATE = new Date(Long.MIN_VALUE);
|
||||
private static final Date MAX_DATE = new Date(Long.MAX_VALUE);
|
||||
|
||||
@RepeatedTest(100)
|
||||
void givenARange_WhenGenTimestamp_ShouldBeInRange() {
|
||||
long aDay = TimeUnit.DAYS.toMillis(1);
|
||||
long now = new Date().getTime();
|
||||
|
||||
Date hundredYearsAgo = new Date(now - aDay * 365 * 100);
|
||||
Date tenDaysAgo = new Date(now - aDay * 10);
|
||||
|
||||
Date random = LegacyRandomDateTimes.between(hundredYearsAgo, tenDaysAgo);
|
||||
assertThat(random).isBetween(hundredYearsAgo, tenDaysAgo);
|
||||
}
|
||||
|
||||
@RepeatedTest(100)
|
||||
void givenNoRange_WhenGenTimestamp_ShouldGenerateRandomTimestamps() {
|
||||
Date random = LegacyRandomDateTimes.timestamp();
|
||||
|
||||
assertThat(random)
|
||||
.isNotNull()
|
||||
.isBetween(MIN_DATE, MAX_DATE);
|
||||
}
|
||||
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
package com.baeldung.random;
|
||||
|
||||
import org.junit.jupiter.api.RepeatedTest;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
class RandomDateTimesUnitTest {
|
||||
|
||||
@RepeatedTest(100)
|
||||
void givenNoRange_WhenGenTimestamp_ShouldGenerateRandomTimestamps() {
|
||||
Instant random = RandomDateTimes.timestamp();
|
||||
|
||||
assertThat(random).isBetween(Instant.MIN, Instant.MAX);
|
||||
}
|
||||
|
||||
@RepeatedTest(100)
|
||||
void givenARange_WhenGenTimestamp_ShouldBeInRange() {
|
||||
Instant hundredYearsAgo = Instant.now().minus(Duration.ofDays(100 * 365));
|
||||
Instant tenDaysAgo = Instant.now().minus(Duration.ofDays(10));
|
||||
|
||||
Instant random = RandomDateTimes.between(hundredYearsAgo, tenDaysAgo);
|
||||
assertThat(random).isBetween(hundredYearsAgo, tenDaysAgo);
|
||||
}
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
package com.baeldung.random;
|
||||
|
||||
import org.junit.jupiter.api.RepeatedTest;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.Month;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
class RandomDatesUnitTest {
|
||||
|
||||
@RepeatedTest(100)
|
||||
void givenNoRange_WhenGenDate_ShouldGenerateRandomDates() {
|
||||
LocalDate randomDay = RandomDates.date();
|
||||
|
||||
assertThat(randomDay).isAfter(LocalDate.MIN).isBefore(LocalDate.MAX);
|
||||
}
|
||||
|
||||
@RepeatedTest(100)
|
||||
void givenARange_WhenGenDate_ShouldBeInRange() {
|
||||
LocalDate start = LocalDate.of(1989, Month.OCTOBER, 14);
|
||||
LocalDate end = LocalDate.now();
|
||||
|
||||
LocalDate random = RandomDates.between(start, end);
|
||||
assertThat(random).isAfter(start).isBefore(end);
|
||||
}
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
package com.baeldung.random;
|
||||
|
||||
import org.junit.jupiter.api.RepeatedTest;
|
||||
|
||||
import java.time.LocalTime;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
class RandomTimesUnitTest {
|
||||
|
||||
@RepeatedTest(100)
|
||||
void givenARange_WhenGenTime_ShouldBeInRange() {
|
||||
LocalTime morning = LocalTime.of(8, 30);
|
||||
LocalTime randomTime = RandomTimes.between(LocalTime.MIDNIGHT, morning);
|
||||
|
||||
assertThat(randomTime)
|
||||
.isAfter(LocalTime.MIDNIGHT).isBefore(morning)
|
||||
.isAfter(LocalTime.MIN).isBefore(LocalTime.MAX);
|
||||
}
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
package com.baeldung.trywithresource;
|
||||
|
||||
public class AutoCloseableMain {
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
orderOfClosingResources();
|
||||
}
|
||||
|
||||
private static void orderOfClosingResources() throws Exception {
|
||||
try (AutoCloseableResourcesFirst af = new AutoCloseableResourcesFirst();
|
||||
AutoCloseableResourcesSecond as = new AutoCloseableResourcesSecond()) {
|
||||
af.doSomething();
|
||||
as.doSomething();
|
||||
}
|
||||
}
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package com.baeldung.trywithresource;
|
||||
|
||||
public class AutoCloseableResourcesFirst implements AutoCloseable {
|
||||
|
||||
public AutoCloseableResourcesFirst() {
|
||||
System.out.println("Constructor -> AutoCloseableResources_First");
|
||||
}
|
||||
|
||||
public void doSomething() {
|
||||
System.out.println("Something -> AutoCloseableResources_First");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws Exception {
|
||||
System.out.println("Closed AutoCloseableResources_First");
|
||||
}
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package com.baeldung.trywithresource;
|
||||
|
||||
public class AutoCloseableResourcesSecond implements AutoCloseable {
|
||||
|
||||
public AutoCloseableResourcesSecond() {
|
||||
System.out.println("Constructor -> AutoCloseableResources_Second");
|
||||
}
|
||||
|
||||
public void doSomething() {
|
||||
System.out.println("Something -> AutoCloseableResources_Second");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws Exception {
|
||||
System.out.println("Closed AutoCloseableResources_Second");
|
||||
}
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
package com.baeldung.trywithresource;
|
||||
|
||||
public class MyResource implements AutoCloseable {
|
||||
@Override
|
||||
public void close() throws Exception {
|
||||
System.out.println("Closed MyResource");
|
||||
}
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
package com.baeldung.scanner;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.util.NoSuchElementException;
|
||||
import java.util.Scanner;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class JavaScannerUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenReadingLines_thenCorrect() {
|
||||
String input = "Scanner\nTest\n";
|
||||
try (Scanner scanner = new Scanner(input)) {
|
||||
assertEquals("Scanner", scanner.nextLine());
|
||||
assertEquals("Test", scanner.nextLine());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenReadingPartialLines_thenCorrect() {
|
||||
String input = "Scanner\n";
|
||||
try (Scanner scanner = new Scanner(input)) {
|
||||
scanner.useDelimiter("");
|
||||
scanner.next();
|
||||
assertEquals("canner", scanner.nextLine());
|
||||
}
|
||||
}
|
||||
|
||||
@Test(expected = NoSuchElementException.class)
|
||||
public void givenNoNewLine_whenReadingNextLine_thenThrowNoSuchElementException() {
|
||||
try (Scanner scanner = new Scanner("")) {
|
||||
String result = scanner.nextLine();
|
||||
}
|
||||
}
|
||||
|
||||
@Test(expected = IllegalStateException.class)
|
||||
public void givenScannerIsClosed_whenReadingNextLine_thenThrowIllegalStateException() {
|
||||
Scanner scanner = new Scanner("");
|
||||
scanner.close();
|
||||
String result = scanner.nextLine();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
## Java String Operations
|
||||
|
||||
This module contains articles about string operations.
|
||||
|
||||
### Relevant Articles:
|
||||
- [Concatenating Strings In Java](https://www.baeldung.com/java-strings-concatenation)
|
||||
- [Checking for Empty or Blank Strings in Java](https://www.baeldung.com/java-blank-empty-strings)
|
||||
- [String Initialization in Java](https://www.baeldung.com/java-string-initialization)
|
||||
- [String toLowerCase and toUpperCase Methods in Java](https://www.baeldung.com/java-string-convert-case)
|
||||
- [Java String equalsIgnoreCase()](https://www.baeldung.com/java-string-equalsignorecase)
|
||||
- More articles: [[<-- prev]](../core-java-string-operations)
|
||||
@@ -0,0 +1,81 @@
|
||||
<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-string-operations-2</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
<name>core-java-string-operations-2</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-java</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../../parent-java</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>javax.validation</groupId>
|
||||
<artifactId>validation-api</artifactId>
|
||||
<version>${validation-api.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>${guava.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hibernate.validator</groupId>
|
||||
<artifactId>hibernate-validator</artifactId>
|
||||
<version>${hibernate-validator.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.el</groupId>
|
||||
<artifactId>javax.el-api</artifactId>
|
||||
<version>${javax.el-api.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.glassfish.web</groupId>
|
||||
<artifactId>javax.el</artifactId>
|
||||
<version>${javax.el.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hamcrest</groupId>
|
||||
<artifactId>hamcrest-library</artifactId>
|
||||
<version>${org.hamcrest.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>core-java-string-operations-2</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
<validation-api.version>2.0.0.Final</validation-api.version>
|
||||
<commons-lang3.version>3.8.1</commons-lang3.version>
|
||||
<guava.version>27.0.1-jre</guava.version>
|
||||
<hibernate-validator.version>6.0.2.Final</hibernate-validator.version>
|
||||
<javax.el-api.version>3.0.0</javax.el-api.version>
|
||||
<javax.el.version>2.2.6</javax.el.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
package com.baeldung.emptystrings;
|
||||
|
||||
class EmptyStringCheck {
|
||||
|
||||
boolean isEmptyString(String string) {
|
||||
return string == null || string.isEmpty();
|
||||
}
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
package com.baeldung.emptystrings;
|
||||
|
||||
class Java5EmptyStringCheck {
|
||||
|
||||
boolean isEmptyString(String string) {
|
||||
return string == null || string.length() == 0;
|
||||
}
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
package com.baeldung.emptystrings;
|
||||
|
||||
class PlainJavaBlankStringCheck {
|
||||
|
||||
boolean isBlankString(String string) {
|
||||
return string == null || string.trim().isEmpty();
|
||||
}
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package com.baeldung.emptystrings;
|
||||
|
||||
import javax.validation.constraints.Pattern;
|
||||
|
||||
class SomeClassWithValidations {
|
||||
|
||||
@Pattern(regexp = "\\A(?!\\s*\\Z).+")
|
||||
private String someString;
|
||||
|
||||
SomeClassWithValidations setSomeString(String someString) {
|
||||
this.someString = someString;
|
||||
return this;
|
||||
}
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
package com.baeldung.changecase;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Locale;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class ToLowerCaseUnitTest {
|
||||
|
||||
private static final Locale TURKISH = new Locale("tr");
|
||||
private String name = "John Doe";
|
||||
private String foreignUppercase = "\u0049";
|
||||
|
||||
@Test
|
||||
public void givenMixedCaseString_WhenToLowerCase_ThenResultIsLowerCase() {
|
||||
assertEquals("john doe", name.toLowerCase());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenForeignString_WhenToLowerCaseWithoutLocale_ThenResultIsLowerCase() {
|
||||
assertEquals("\u0069", foreignUppercase.toLowerCase());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenForeignString_WhenToLowerCaseWithLocale_ThenResultIsLowerCase() {
|
||||
assertEquals("\u0131", foreignUppercase.toLowerCase(TURKISH));
|
||||
}
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
package com.baeldung.changecase;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Locale;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class ToUpperCaseUnitTest {
|
||||
|
||||
private static final Locale TURKISH = new Locale("tr");
|
||||
private String name = "John Doe";
|
||||
private String foreignLowercase = "\u0069";
|
||||
|
||||
@Test
|
||||
public void givenMixedCaseString_WhenToUpperCase_ThenResultIsUpperCase() {
|
||||
assertEquals("JOHN DOE", name.toUpperCase());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenForeignString_WhenToUpperCaseWithoutLocale_ThenResultIsUpperCase() {
|
||||
assertEquals("\u0049", foreignLowercase.toUpperCase());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenForeignString_WhenToUpperCaseWithLocale_ThenResultIsUpperCase() {
|
||||
assertEquals("\u0130", foreignLowercase.toUpperCase(TURKISH));
|
||||
}
|
||||
}
|
||||
+138
@@ -0,0 +1,138 @@
|
||||
package com.baeldung.emptystrings;
|
||||
|
||||
import com.google.common.base.Strings;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.junit.Test;
|
||||
|
||||
import javax.validation.ConstraintViolation;
|
||||
import javax.validation.Validation;
|
||||
import javax.validation.Validator;
|
||||
import javax.validation.ValidatorFactory;
|
||||
import java.util.Set;
|
||||
|
||||
import static org.hamcrest.Matchers.iterableWithSize;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class EmptyStringsUnitTest {
|
||||
|
||||
private String emptyString = "";
|
||||
private String blankString = " \n\t ";
|
||||
private String nonEmptyString = " someString ";
|
||||
|
||||
/*
|
||||
* EmptyStringCheck
|
||||
*/
|
||||
@Test
|
||||
public void givenSomeEmptyString_thenEmptyStringCheckIsEmptyStringReturnsTrue() {
|
||||
assertTrue(new EmptyStringCheck().isEmptyString(emptyString));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSomeNonEmptyString_thenEmptyStringCheckIsEmptyStringReturnsFalse() {
|
||||
assertFalse(new EmptyStringCheck().isEmptyString(nonEmptyString));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSomeBlankString_thenEmptyStringCheckIsEmptyStringReturnsFalse() {
|
||||
assertFalse(new EmptyStringCheck().isEmptyString(blankString));
|
||||
}
|
||||
|
||||
/*
|
||||
* Java5EmptyStringCheck
|
||||
*/
|
||||
@Test
|
||||
public void givenSomeEmptyString_thenJava5EmptyStringCheckIsEmptyStringReturnsTrue() {
|
||||
assertTrue(new Java5EmptyStringCheck().isEmptyString(emptyString));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSomeNonEmptyString_thenJava5EmptyStringCheckIsEmptyStringReturnsFalse() {
|
||||
assertFalse(new Java5EmptyStringCheck().isEmptyString(nonEmptyString));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSomeBlankString_thenJava5EmptyStringCheckIsEmptyStringReturnsFalse() {
|
||||
assertFalse(new Java5EmptyStringCheck().isEmptyString(blankString));
|
||||
}
|
||||
|
||||
/*
|
||||
* PlainJavaBlankStringCheck
|
||||
*/
|
||||
@Test
|
||||
public void givenSomeEmptyString_thenPlainJavaBlankStringCheckIsBlankStringReturnsTrue() {
|
||||
assertTrue(new PlainJavaBlankStringCheck().isBlankString(emptyString));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSomeNonEmptyString_thenPlainJavaBlankStringCheckIsBlankStringReturnsFalse() {
|
||||
assertFalse(new PlainJavaBlankStringCheck().isBlankString(nonEmptyString));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSomeBlankString_thenPlainJavaBlankStringCheckIsBlankStringReturnsTrue() {
|
||||
assertTrue(new PlainJavaBlankStringCheck().isBlankString(blankString));
|
||||
}
|
||||
|
||||
/*
|
||||
* Apache Commons Lang StringUtils
|
||||
*/
|
||||
@Test
|
||||
public void givenSomeEmptyString_thenStringUtilsIsBlankReturnsTrue() {
|
||||
assertTrue(StringUtils.isBlank(emptyString));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSomeNonEmptyString_thenStringUtilsIsBlankReturnsFalse() {
|
||||
assertFalse(StringUtils.isBlank(nonEmptyString));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSomeBlankString_thenStringUtilsIsBlankReturnsTrue() {
|
||||
assertTrue(StringUtils.isBlank(blankString));
|
||||
}
|
||||
|
||||
/*
|
||||
* Google Guava Strings
|
||||
*/
|
||||
@Test
|
||||
public void givenSomeEmptyString_thenStringsIsNullOrEmptyStringReturnsTrue() {
|
||||
assertTrue(Strings.isNullOrEmpty(emptyString));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSomeNonEmptyString_thenStringsIsNullOrEmptyStringReturnsFalse() {
|
||||
assertFalse(Strings.isNullOrEmpty(nonEmptyString));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSomeBlankString_thenStringsIsNullOrEmptyStringReturnsFalse() {
|
||||
assertFalse(Strings.isNullOrEmpty(blankString));
|
||||
}
|
||||
|
||||
/*
|
||||
* Bean Validation
|
||||
*/
|
||||
private ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
|
||||
private Validator validator = factory.getValidator();
|
||||
|
||||
@Test
|
||||
public void givenSomeEmptyString_thenBeanValidationReturnsViolations() {
|
||||
SomeClassWithValidations someClassWithValidations = new SomeClassWithValidations().setSomeString(emptyString);
|
||||
Set<ConstraintViolation<SomeClassWithValidations>> violations = validator.validate(someClassWithValidations);
|
||||
assertThat(violations, iterableWithSize(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSomeNonEmptyString_thenBeanValidationValidatesWithoutViolations() {
|
||||
SomeClassWithValidations someClassWithValidations = new SomeClassWithValidations().setSomeString(nonEmptyString);
|
||||
Set<ConstraintViolation<SomeClassWithValidations>> violations = validator.validate(someClassWithValidations);
|
||||
assertThat(violations, iterableWithSize(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSomeBlankString_thenBeanValidationReturnsViolations() {
|
||||
SomeClassWithValidations someClassWithValidations = new SomeClassWithValidations().setSomeString(blankString);
|
||||
Set<ConstraintViolation<SomeClassWithValidations>> violations = validator.validate(someClassWithValidations);
|
||||
assertThat(violations, iterableWithSize(1));
|
||||
}
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package com.baeldung.equalsIgnoreCase;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class StringEqualsIgnoreCaseUnitTest {
|
||||
private String string1 = "equals ignore case";
|
||||
private String string2 = "EQUALS IGNORE CASE";
|
||||
|
||||
@Test
|
||||
public void givenEqualStringsWithDifferentCase_whenUsingEqualsIgnoreCase_ThenTheyAreEqual() {
|
||||
assertThat(string1.equalsIgnoreCase(string2)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEqualStringsWithDifferentCase_whenUsingApacheCommonsEqualsIgnoreCase_ThenTheyAreEqual() {
|
||||
assertThat(StringUtils.equalsIgnoreCase(string1, string2)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAStringAndNullValue_whenUsingApacheCommonsEqualsIgnoreCase_ThenTheyAreNotEqual() {
|
||||
assertThat(StringUtils.equalsIgnoreCase(string1, null)).isFalse();
|
||||
}
|
||||
}
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
package com.baeldung.initialization;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class StringInitializationUnitTest {
|
||||
|
||||
private String fieldString;
|
||||
|
||||
void printDeclaredOnlyString() {
|
||||
String localVarString = null;
|
||||
|
||||
System.out.println(localVarString); // compilation error
|
||||
System.out.println(fieldString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDeclaredFeldStringAndNullString_thenCompareEquals() {
|
||||
String localVarString = null;
|
||||
|
||||
assertEquals(fieldString, localVarString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoStringsWithSameLiteral_thenCompareReferencesEquals() {
|
||||
String literalOne = "Baeldung";
|
||||
String literalTwo = "Baeldung";
|
||||
|
||||
assertTrue(literalOne == literalTwo);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoStringsUsingNew_thenCompareReferencesNotEquals() {
|
||||
String newStringOne = new String("Baeldung");
|
||||
String newStringTwo = new String("Baeldung");
|
||||
|
||||
assertFalse(newStringOne == newStringTwo);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmptyLiteralStringsAndNewObject_thenCompareEquals() {
|
||||
String emptyLiteral = "";
|
||||
String emptyNewString = new String("");
|
||||
|
||||
assertEquals(emptyLiteral, emptyNewString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmptyStringObjects_thenCompareEquals() {
|
||||
String emptyNewString = new String("");
|
||||
String emptyNewStringTwo = new String();
|
||||
|
||||
assertEquals(emptyNewString, emptyNewStringTwo);
|
||||
}
|
||||
}
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
package com.baeldung.stringconcatenation;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.StringJoiner;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class StringConcatenationUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenMultipleStrings_whenConcatUsingStringBuilder_checkStringCorrect() {
|
||||
|
||||
StringBuilder stringBuilder = new StringBuilder(100);
|
||||
stringBuilder.append("Baeldung");
|
||||
stringBuilder.append(" is");
|
||||
stringBuilder.append(" awesome");
|
||||
|
||||
assertEquals("Baeldung is awesome", stringBuilder.toString());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMultipleString_whenConcatUsingAdditionOperator_checkStringCorrect() {
|
||||
|
||||
String myString = "The " + "quick " + "brown " + "fox...";
|
||||
|
||||
assertEquals("The quick brown fox...", myString);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenMultipleStrings_whenConcatUsingStringFormat_checkStringCorrect() {
|
||||
|
||||
String myString = String.format("%s %s %.2f %s %s, %s...", "I",
|
||||
"ate",
|
||||
2.5056302,
|
||||
"blueberry",
|
||||
"pies",
|
||||
"oops");
|
||||
|
||||
|
||||
assertEquals("I ate 2.51 blueberry pies, oops...", myString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMultipleStrings_whenStringConcatUsed_checkStringCorrect() {
|
||||
|
||||
String myString = "Both".concat(" fickle")
|
||||
.concat(" dwarves")
|
||||
.concat(" jinx")
|
||||
.concat(" my")
|
||||
.concat(" pig")
|
||||
.concat(" quiz");
|
||||
|
||||
assertEquals("Both fickle dwarves jinx my pig quiz", myString);
|
||||
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMultipleStrings_whenStringJoinUsed_checkStringCorrect() {
|
||||
|
||||
String[] strings = {"I'm", "running", "out", "of", "pangrams!"};
|
||||
|
||||
String myString = String.join(" ", strings);
|
||||
|
||||
assertEquals("I'm running out of pangrams!", myString);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMultipleStrings_whenStringJoinerUsed_checkStringCorrect() {
|
||||
|
||||
StringJoiner fruitJoiner = new StringJoiner(", ");
|
||||
fruitJoiner.add("Apples");
|
||||
fruitJoiner.add("Oranges");
|
||||
fruitJoiner.add("Bananas");
|
||||
|
||||
assertEquals("Apples, Oranges, Bananas", fruitJoiner.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMultipleStrings_whenArrayJoiner_checkStringCorrect() {
|
||||
|
||||
String[] myFavouriteLanguages = {"Java", "JavaScript", "Python"};
|
||||
|
||||
String toString = Arrays.toString(myFavouriteLanguages);
|
||||
|
||||
assertEquals("[Java, JavaScript, Python]", toString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArrayListOfStrings_whenCollectorsJoin_checkStringCorrect() {
|
||||
|
||||
List<String> awesomeAnimals = Arrays.asList("Shark", "Panda", "Armadillo");
|
||||
|
||||
String animalString = awesomeAnimals.stream().collect(Collectors.joining(", "));
|
||||
|
||||
assertEquals("Shark, Panda, Armadillo", animalString);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
## Java String Operations
|
||||
|
||||
This module contains articles about string operations.
|
||||
|
||||
### Relevant Articles:
|
||||
- [Comparing Strings in Java](https://www.baeldung.com/java-compare-strings)
|
||||
- [Check If a String Is Numeric in Java](https://www.baeldung.com/java-check-string-number)
|
||||
- [Get Substring from String in Java](https://www.baeldung.com/java-substring)
|
||||
- [Split a String in Java](https://www.baeldung.com/java-split-string)
|
||||
- [Common String Operations in Java](https://www.baeldung.com/java-string-operations)
|
||||
- [Java toString() Method](https://www.baeldung.com/java-tostring)
|
||||
- [String Operations with Java Streams](https://www.baeldung.com/java-stream-operations-on-strings)
|
||||
- [Adding a Newline Character to a String in Java](https://www.baeldung.com/java-string-newline)
|
||||
- [Check If a String Contains a Substring](https://www.baeldung.com/java-string-contains-substring)
|
||||
- [Java Base64 Encoding and Decoding](https://www.baeldung.com/java-base64-encode-and-decode)
|
||||
- More articles: [[next -->]](../core-java-string-operations-2)
|
||||
@@ -0,0 +1,66 @@
|
||||
<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-string-operations</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
<name>core-java-string-operations</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-java</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../../parent-java</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-core</artifactId>
|
||||
<version>${jmh-core.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>log4j</groupId>
|
||||
<artifactId>log4j</artifactId>
|
||||
<version>${log4j.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-generator-annprocess</artifactId>
|
||||
<version>${jmh-generator.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>commons-codec</groupId>
|
||||
<artifactId>commons-codec</artifactId>
|
||||
<version>${commons-codec.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>core-java-string-operations</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<commons-lang3.version>3.8.1</commons-lang3.version>
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
<commons-codec.version>1.10</commons-codec.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
package com.baeldung.isnumeric;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import org.openjdk.jmh.annotations.Benchmark;
|
||||
import org.openjdk.jmh.annotations.BenchmarkMode;
|
||||
import org.openjdk.jmh.annotations.Mode;
|
||||
import org.openjdk.jmh.annotations.OutputTimeUnit;
|
||||
import org.openjdk.jmh.annotations.Scope;
|
||||
import org.openjdk.jmh.annotations.State;
|
||||
import org.openjdk.jmh.runner.Runner;
|
||||
import org.openjdk.jmh.runner.RunnerException;
|
||||
import org.openjdk.jmh.runner.options.Options;
|
||||
import org.openjdk.jmh.runner.options.OptionsBuilder;
|
||||
|
||||
public class Benchmarking {
|
||||
public static void main(String[] args) throws RunnerException {
|
||||
Options opt = new OptionsBuilder().include(Benchmarking.class.getSimpleName())
|
||||
.forks(1)
|
||||
.build();
|
||||
|
||||
new Runner(opt).run();
|
||||
}
|
||||
|
||||
@State(Scope.Thread)
|
||||
public static class ExecutionPlan {
|
||||
public String number = Integer.toString(Integer.MAX_VALUE);
|
||||
public boolean isNumber = false;
|
||||
public IsNumeric isNumeric = new IsNumeric();
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||
public void usingCoreJava(ExecutionPlan plan) {
|
||||
plan.isNumber = plan.isNumeric.usingCoreJava(plan.number);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||
public void usingRegularExpressions(ExecutionPlan plan) {
|
||||
plan.isNumber = plan.isNumeric.usingRegularExpressions(plan.number);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||
public void usingNumberUtils_isCreatable(ExecutionPlan plan) {
|
||||
plan.isNumber = plan.isNumeric.usingNumberUtils_isCreatable(plan.number);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||
public void usingNumberUtils_isParsable(ExecutionPlan plan) {
|
||||
plan.isNumber = plan.isNumeric.usingNumberUtils_isParsable(plan.number);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||
public void usingStringUtils_isNumeric(ExecutionPlan plan) {
|
||||
plan.isNumber = plan.isNumeric.usingStringUtils_isNumeric(plan.number);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||
public void usingStringUtils_isNumericSpace(ExecutionPlan plan) {
|
||||
plan.isNumber = plan.isNumeric.usingStringUtils_isNumericSpace(plan.number);
|
||||
}
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package com.baeldung.isnumeric;
|
||||
|
||||
import java.util.Scanner;
|
||||
|
||||
public class CheckIntegerInput {
|
||||
|
||||
public static void main(String[] args) {
|
||||
try (Scanner scanner = new Scanner(System.in)) {
|
||||
System.out.println("Enter an integer : ");
|
||||
|
||||
if (scanner.hasNextInt()) {
|
||||
System.out.println("You entered : " + scanner.nextInt());
|
||||
} else {
|
||||
System.out.println("The input is not an integer");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
package com.baeldung.isnumeric;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.apache.commons.lang3.math.NumberUtils;
|
||||
|
||||
public class IsNumeric {
|
||||
public boolean usingCoreJava(String strNum) {
|
||||
try {
|
||||
Double.parseDouble(strNum);
|
||||
} catch (NumberFormatException | NullPointerException nfe) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public boolean usingRegularExpressions(String strNum) {
|
||||
return strNum.matches("-?\\d+(\\.\\d+)?");
|
||||
}
|
||||
|
||||
public boolean usingNumberUtils_isCreatable(String strNum) {
|
||||
return NumberUtils.isCreatable(strNum);
|
||||
}
|
||||
|
||||
public boolean usingNumberUtils_isParsable(String strNum) {
|
||||
return NumberUtils.isParsable(strNum);
|
||||
}
|
||||
|
||||
public boolean usingStringUtils_isNumeric(String strNum) {
|
||||
return StringUtils.isNumeric(strNum);
|
||||
}
|
||||
|
||||
public boolean usingStringUtils_isNumericSpace(String strNum) {
|
||||
return StringUtils.isNumericSpace(strNum);
|
||||
}
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
package com.baeldung.isnumeric;
|
||||
|
||||
import org.apache.log4j.Logger;
|
||||
|
||||
public class IsNumericDriver {
|
||||
private static Logger LOG = Logger.getLogger(IsNumericDriver.class);
|
||||
|
||||
private static IsNumeric isNumeric = new IsNumeric();
|
||||
|
||||
public static void main(String[] args) {
|
||||
LOG.info("Testing all methods...");
|
||||
|
||||
boolean res = isNumeric.usingCoreJava("1001");
|
||||
LOG.info("Using Core Java : " + res);
|
||||
|
||||
res = isNumeric.usingRegularExpressions("1001");
|
||||
LOG.info("Using Regular Expressions : " + res);
|
||||
|
||||
res = isNumeric.usingNumberUtils_isCreatable("1001");
|
||||
LOG.info("Using NumberUtils.isCreatable : " + res);
|
||||
|
||||
res = isNumeric.usingNumberUtils_isParsable("1001");
|
||||
LOG.info("Using NumberUtils.isParsable : " + res);
|
||||
|
||||
res = isNumeric.usingStringUtils_isNumeric("1001");
|
||||
LOG.info("Using StringUtils.isNumeric : " + res);
|
||||
|
||||
res = isNumeric.usingStringUtils_isNumericSpace("1001");
|
||||
LOG.info("Using StringUtils.isNumericSpace : " + res);
|
||||
}
|
||||
}
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
package com.baeldung.newline;
|
||||
|
||||
public class AddingNewLineToString {
|
||||
|
||||
public static void main(String[] args) {
|
||||
String line1 = "Humpty Dumpty sat on a wall.";
|
||||
String line2 = "Humpty Dumpty had a great fall.";
|
||||
String rhyme = "";
|
||||
|
||||
System.out.println("***New Line in a String in Java***");
|
||||
//1. Using "\n"
|
||||
System.out.println("1. Using \\n");
|
||||
rhyme = line1 + "\n" + line2;
|
||||
System.out.println(rhyme);
|
||||
|
||||
//2. Using "\r\n"
|
||||
System.out.println("2. Using \\r\\n");
|
||||
rhyme = line1 + "\r\n" + line2;
|
||||
System.out.println(rhyme);
|
||||
|
||||
//3. Using "\r"
|
||||
System.out.println("3. Using \\r");
|
||||
rhyme = line1 + "\r" + line2;
|
||||
System.out.println(rhyme);
|
||||
|
||||
//4. Using "\n\r" Note that this is not same as "\r\n"
|
||||
// Using "\n\r" is equivalent to adding two lines
|
||||
System.out.println("4. Using \\n\\r");
|
||||
rhyme = line1 + "\n\r" + line2;
|
||||
System.out.println(rhyme);
|
||||
|
||||
//5. Using System.lineSeparator()
|
||||
System.out.println("5. Using System.lineSeparator()");
|
||||
rhyme = line1 + System.lineSeparator() + line2;
|
||||
System.out.println(rhyme);
|
||||
|
||||
//6. Using System.getProperty("line.separator")
|
||||
System.out.println("6. Using System.getProperty(\"line.separator\")");
|
||||
rhyme = line1 + System.getProperty("line.separator") + line2;
|
||||
System.out.println(rhyme);
|
||||
|
||||
System.out.println("***HTML to rendered in a browser***");
|
||||
//1. Line break for HTML using <br>
|
||||
System.out.println("1. Line break for HTML using <br>");
|
||||
rhyme = line1 + "<br>" + line2;
|
||||
System.out.println(rhyme);
|
||||
|
||||
//2. Line break for HTML using “ ”
|
||||
System.out.println("2. Line break for HTML using ");
|
||||
rhyme = line1 + " " + line2;
|
||||
System.out.println(rhyme);
|
||||
|
||||
//3. Line break for HTML using “ ”
|
||||
System.out.println("3. Line break for HTML using ");
|
||||
rhyme = line1 + " " + line2;
|
||||
System.out.println(rhyme);
|
||||
|
||||
//4. Line break for HTML using “
 ;”
|
||||
System.out.println("4. Line break for HTML using ");
|
||||
rhyme = line1 + " " + line2;
|
||||
System.out.println(rhyme);
|
||||
|
||||
//5. Line break for HTML using \n”
|
||||
System.out.println("5. Line break for HTML using \\n");
|
||||
rhyme = line1 + "\n" + line2;
|
||||
System.out.println(rhyme);
|
||||
}
|
||||
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
package com.baeldung.streamoperations;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public class JoinerSplitter {
|
||||
|
||||
public static String join ( String[] arrayOfString ) {
|
||||
return Arrays.asList(arrayOfString)
|
||||
.stream()
|
||||
.map(x -> x)
|
||||
.collect(Collectors.joining(","));
|
||||
}
|
||||
|
||||
public static String joinWithPrefixPostFix ( String[] arrayOfString ) {
|
||||
return Arrays.asList(arrayOfString)
|
||||
.stream()
|
||||
.map(x -> x)
|
||||
.collect(Collectors.joining(",","[","]"));
|
||||
}
|
||||
|
||||
public static List<String> split ( String str ) {
|
||||
return Stream.of(str.split(","))
|
||||
.map (elem -> new String(elem))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public static List<Character> splitToListOfChar ( String str ) {
|
||||
return str.chars()
|
||||
.mapToObj(item -> (char) item)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public static Map<String, String> arrayToMap(String[] arrayOfString) {
|
||||
return Arrays.asList(arrayOfString)
|
||||
.stream()
|
||||
.map(str -> str.split(":"))
|
||||
.collect(Collectors.<String[], String, String>toMap(str -> str[0], str -> str[1]));
|
||||
}
|
||||
|
||||
}
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
package com.baeldung.substringsearch;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.openjdk.jmh.annotations.*;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Based on https://github.com/tedyoung/indexof-contains-benchmark
|
||||
*/
|
||||
@Fork(5)
|
||||
@State(Scope.Benchmark)
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||
public class SubstringSearchPerformanceComparison {
|
||||
|
||||
private String message;
|
||||
|
||||
private Pattern pattern;
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
org.openjdk.jmh.Main.main(args);
|
||||
}
|
||||
|
||||
@Setup
|
||||
public void setup() {
|
||||
message = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum";
|
||||
pattern = Pattern.compile("(?<!\\S)" + "eiusmod" + "(?!\\S)");
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public int indexOf() {
|
||||
return message.indexOf("eiusmod");
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public boolean contains() {
|
||||
return message.contains("eiusmod");
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public boolean containsStringUtilsIgnoreCase() {
|
||||
return StringUtils.containsIgnoreCase(message, "eiusmod");
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public boolean searchWithPattern() {
|
||||
return pattern.matcher(message).find();
|
||||
}
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
package com.baeldung.tostring;
|
||||
|
||||
public class Customer {
|
||||
private String firstName;
|
||||
private String lastName;
|
||||
|
||||
public String getFirstName() {
|
||||
return firstName;
|
||||
}
|
||||
|
||||
public void setFirstName(String firstName) {
|
||||
this.firstName = firstName;
|
||||
}
|
||||
|
||||
public String getLastName() {
|
||||
return lastName;
|
||||
}
|
||||
|
||||
public void setLastName(String lastName) {
|
||||
this.lastName = lastName;
|
||||
}
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
package com.baeldung.tostring;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
public class CustomerArrayToString extends Customer {
|
||||
private Order[] orders;
|
||||
|
||||
public Order[] getOrders() {
|
||||
return orders;
|
||||
}
|
||||
|
||||
public void setOrders(Order[] orders) {
|
||||
this.orders = orders;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Customer [orders=" + Arrays.toString(orders) + ", getFirstName()=" + getFirstName() + ", getLastName()=" + getLastName() + "]";
|
||||
}
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package com.baeldung.tostring;
|
||||
|
||||
public class CustomerComplexObjectToString extends Customer {
|
||||
private Order order;
|
||||
|
||||
public Order getOrder() {
|
||||
return order;
|
||||
}
|
||||
|
||||
public void setOrder(Order order) {
|
||||
this.order = order;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Customer [order=" + order + ", getFirstName()=" + getFirstName() + ", getLastName()=" + getLastName() + "]";
|
||||
}
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package com.baeldung.tostring;
|
||||
|
||||
public class CustomerPrimitiveToString extends Customer {
|
||||
private long balance;
|
||||
|
||||
public long getBalance() {
|
||||
return balance;
|
||||
}
|
||||
|
||||
public void setBalance(long balance) {
|
||||
this.balance = balance;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Customer [balance=" + balance + ", getFirstName()=" + getFirstName() + ", getLastName()=" + getLastName() + "]";
|
||||
}
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
package com.baeldung.tostring;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
|
||||
|
||||
public class CustomerReflectionToString extends Customer {
|
||||
|
||||
private Integer score;
|
||||
private List<String> orders;
|
||||
private StringBuffer fullname;
|
||||
|
||||
public Integer getScore() {
|
||||
return score;
|
||||
}
|
||||
|
||||
public void setScore(Integer score) {
|
||||
this.score = score;
|
||||
}
|
||||
|
||||
public List<String> getOrders() {
|
||||
return orders;
|
||||
}
|
||||
|
||||
public void setOrders(List<String> orders) {
|
||||
this.orders = orders;
|
||||
}
|
||||
|
||||
public StringBuffer getFullname() {
|
||||
return fullname;
|
||||
}
|
||||
|
||||
public void setFullname(StringBuffer fullname) {
|
||||
this.fullname = fullname;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return ReflectionToStringBuilder.toString(this);
|
||||
}
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
package com.baeldung.tostring;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class CustomerWrapperCollectionToString extends Customer {
|
||||
private Integer score;
|
||||
private List<String> orders;
|
||||
private StringBuffer fullname;
|
||||
|
||||
public Integer getScore() {
|
||||
return score;
|
||||
}
|
||||
|
||||
public void setScore(Integer score) {
|
||||
this.score = score;
|
||||
}
|
||||
|
||||
public List<String> getOrders() {
|
||||
return orders;
|
||||
}
|
||||
|
||||
public void setOrders(List<String> orders) {
|
||||
this.orders = orders;
|
||||
}
|
||||
|
||||
public StringBuffer getFullname() {
|
||||
return fullname;
|
||||
}
|
||||
|
||||
public void setFullname(StringBuffer fullname) {
|
||||
this.fullname = fullname;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Customer [score=" + score + ", orders=" + orders + ", fullname=" + fullname + ", getFirstName()=" + getFirstName() + ", getLastName()=" + getLastName() + "]";
|
||||
}
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
package com.baeldung.tostring;
|
||||
|
||||
public class Order {
|
||||
|
||||
private String orderId;
|
||||
private String desc;
|
||||
private long value;
|
||||
private String status;
|
||||
|
||||
public String getOrderId() {
|
||||
return orderId;
|
||||
}
|
||||
|
||||
public void setOrderId(String orderId) {
|
||||
this.orderId = orderId;
|
||||
}
|
||||
|
||||
public String getDesc() {
|
||||
return desc;
|
||||
}
|
||||
|
||||
public void setDesc(String desc) {
|
||||
this.desc = desc;
|
||||
}
|
||||
|
||||
public long getValue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
public void setValue(long value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public String getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public void setStatus(String status) {
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Order [orderId=" + orderId + ", desc=" + desc + ", value=" + value + "]";
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
# Root logger option
|
||||
log4j.rootLogger=DEBUG, stdout
|
||||
|
||||
# Redirect log messages to console
|
||||
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
|
||||
log4j.appender.stdout.Target=System.out
|
||||
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
|
||||
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
package com.baeldung.base64encodinganddecoding;
|
||||
|
||||
import org.apache.commons.codec.binary.Base64;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.UnsupportedEncodingException;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class ApacheCommonsEncodeDecodeUnitTest {
|
||||
|
||||
// tests
|
||||
|
||||
@Test
|
||||
public void whenStringIsEncoded() throws UnsupportedEncodingException {
|
||||
final String originalInput = "test input";
|
||||
final Base64 base64 = new Base64();
|
||||
final String encodedString = new String(base64.encode(originalInput.getBytes()));
|
||||
|
||||
assertNotNull(encodedString);
|
||||
assertNotEquals(originalInput, encodedString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenStringIsEncoded_thenStringCanBeDecoded() throws UnsupportedEncodingException {
|
||||
final String originalInput = "test input";
|
||||
final Base64 base64 = new Base64();
|
||||
final String encodedString = new String(base64.encode(originalInput.getBytes()));
|
||||
|
||||
final String decodedString = new String(base64.decode(encodedString.getBytes()));
|
||||
|
||||
assertNotNull(decodedString);
|
||||
assertEquals(originalInput, decodedString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenStringIsEncodedUsingStaticMethod() throws UnsupportedEncodingException {
|
||||
final String originalInput = "test input";
|
||||
final String encodedString = new String(Base64.encodeBase64(originalInput.getBytes()));
|
||||
|
||||
assertNotNull(encodedString);
|
||||
assertNotEquals(originalInput, encodedString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenStringIsEncodedUsingStaticMethod_thenStringCanBeDecodedUsingStaticMethod() throws UnsupportedEncodingException {
|
||||
final String originalInput = "test input";
|
||||
final String encodedString = new String(Base64.encodeBase64(originalInput.getBytes()));
|
||||
|
||||
final String decodedString = new String(Base64.decodeBase64(encodedString.getBytes()));
|
||||
|
||||
assertNotNull(decodedString);
|
||||
assertEquals(originalInput, decodedString);
|
||||
}
|
||||
|
||||
}
|
||||
+109
@@ -0,0 +1,109 @@
|
||||
package com.baeldung.base64encodinganddecoding;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.util.Base64;
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class Java8EncodeDecodeUnitTest {
|
||||
|
||||
// tests
|
||||
|
||||
@Test
|
||||
public void whenStringIsEncoded_thenOk() throws UnsupportedEncodingException {
|
||||
final String originalInput = "test input";
|
||||
final String encodedString = Base64.getEncoder().encodeToString(originalInput.getBytes());
|
||||
|
||||
assertNotNull(encodedString);
|
||||
assertNotEquals(originalInput, encodedString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenStringIsEncoded_thenStringCanBeDecoded() throws UnsupportedEncodingException {
|
||||
final String originalInput = "test input";
|
||||
final String encodedString = Base64.getEncoder().encodeToString(originalInput.getBytes());
|
||||
|
||||
final byte[] decodedBytes = Base64.getDecoder().decode(encodedString);
|
||||
final String decodedString = new String(decodedBytes);
|
||||
|
||||
assertNotNull(decodedString);
|
||||
assertEquals(originalInput, decodedString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenStringIsEncodedWithoutPadding_thenOk() throws UnsupportedEncodingException {
|
||||
final String originalInput = "test input";
|
||||
final String encodedString = Base64.getEncoder().withoutPadding().encodeToString(originalInput.getBytes());
|
||||
|
||||
assertNotNull(encodedString);
|
||||
assertNotEquals(originalInput, encodedString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenStringIsEncodedWithoutPadding_thenStringCanBeDecoded() throws UnsupportedEncodingException {
|
||||
final String originalInput = "test input";
|
||||
final String encodedString = Base64.getEncoder().withoutPadding().encodeToString(originalInput.getBytes());
|
||||
|
||||
final byte[] decodedBytes = Base64.getDecoder().decode(encodedString);
|
||||
final String decodedString = new String(decodedBytes);
|
||||
|
||||
assertNotNull(decodedString);
|
||||
assertEquals(originalInput, decodedString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUrlIsEncoded_thenOk() throws UnsupportedEncodingException {
|
||||
final String originalUrl = "https://www.google.co.nz/?gfe_rd=cr&ei=dzbFVf&gws_rd=ssl#q=java";
|
||||
final String encodedUrl = Base64.getUrlEncoder().encodeToString(originalUrl.getBytes());
|
||||
assertNotNull(encodedUrl);
|
||||
assertNotEquals(originalUrl, encodedUrl);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUrlIsEncoded_thenURLCanBeDecoded() throws UnsupportedEncodingException {
|
||||
final String originalUrl = "https://www.google.co.nz/?gfe_rd=cr&ei=dzbFVf&gws_rd=ssl#q=java";
|
||||
final String encodedUrl = Base64.getUrlEncoder().encodeToString(originalUrl.getBytes());
|
||||
|
||||
final byte[] decodedBytes = Base64.getUrlDecoder().decode(encodedUrl.getBytes());
|
||||
final String decodedUrl = new String(decodedBytes);
|
||||
|
||||
assertNotNull(decodedUrl);
|
||||
assertEquals(originalUrl, decodedUrl);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenMimeIsEncoded_thenOk() throws UnsupportedEncodingException {
|
||||
final StringBuilder buffer = getMimeBuffer();
|
||||
|
||||
final byte[] forEncode = buffer.toString().getBytes();
|
||||
final String encodedMime = Base64.getMimeEncoder().encodeToString(forEncode);
|
||||
|
||||
assertNotNull(encodedMime);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenMimeIsEncoded_thenItCanBeDecoded() throws UnsupportedEncodingException {
|
||||
final StringBuilder buffer = getMimeBuffer();
|
||||
|
||||
final byte[] forEncode = buffer.toString().getBytes();
|
||||
final String encodedMime = Base64.getMimeEncoder().encodeToString(forEncode);
|
||||
|
||||
final byte[] decodedBytes = Base64.getMimeDecoder().decode(encodedMime);
|
||||
final String decodedMime = new String(decodedBytes);
|
||||
assertNotNull(decodedMime);
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
private static StringBuilder getMimeBuffer() {
|
||||
final StringBuilder buffer = new StringBuilder();
|
||||
for (int count = 0; count < 10; ++count) {
|
||||
buffer.append(UUID.randomUUID().toString());
|
||||
}
|
||||
return buffer;
|
||||
}
|
||||
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
package com.baeldung.base64encodinganddecoding;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import javax.xml.bind.DatatypeConverter;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Arrays;
|
||||
import java.util.Base64;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class StringToByteArrayUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenConvertStringToByteArrayUsingStringClass_thenOk() {
|
||||
final String originalInput = "test input";
|
||||
byte[] result = originalInput.getBytes();
|
||||
System.out.println(Arrays.toString(result));
|
||||
|
||||
assertEquals(originalInput.length(), result.length);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCharset_whenConvertStringToByteArrayUsingStringClass_thenOk() throws UnsupportedEncodingException {
|
||||
final String originalInput = "test input";
|
||||
byte[] result = originalInput.getBytes(StandardCharsets.UTF_16);
|
||||
System.out.println(Arrays.toString(result));
|
||||
|
||||
assertTrue(originalInput.length() < result.length);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenConvertStringToByteArrayUsingBase64Decoder_thenOk() {
|
||||
final String originalInput = "dGVzdCBpbnB1dA==";
|
||||
byte[] result = Base64.getDecoder().decode(originalInput);
|
||||
|
||||
assertEquals("test input", new String(result));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenConvertStringToByteArrayUsingDatatypeConverter_thenOk() {
|
||||
final String originalInput = "dGVzdCBpbnB1dA==";
|
||||
byte[] result = DatatypeConverter.parseBase64Binary(originalInput);
|
||||
|
||||
assertEquals("test input", new String(result));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenConvertStringToByteArray_thenOk(){
|
||||
String originalInput = "7465737420696E707574";
|
||||
byte[] result = DatatypeConverter.parseHexBinary(originalInput);
|
||||
System.out.println(Arrays.toString(result));
|
||||
|
||||
assertEquals("test input", new String(result));
|
||||
}
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
package com.baeldung.isnumeric;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class CoreJavaIsNumericUnitTest {
|
||||
public static boolean isNumeric(String strNum) {
|
||||
try {
|
||||
double d = Double.parseDouble(strNum);
|
||||
} catch (NumberFormatException | NullPointerException nfe) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingCoreJava_thenTrue() {
|
||||
// Valid Numbers
|
||||
assertThat(isNumeric("22")).isTrue();
|
||||
assertThat(isNumeric("5.05")).isTrue();
|
||||
assertThat(isNumeric("-200")).isTrue();
|
||||
assertThat(isNumeric("10.0d")).isTrue();
|
||||
assertThat(isNumeric(" 22 ")).isTrue();
|
||||
|
||||
// Invalid Numbers
|
||||
assertThat(isNumeric(null)).isFalse();
|
||||
assertThat(isNumeric("")).isFalse();
|
||||
assertThat(isNumeric("abc")).isFalse();
|
||||
}
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
package com.baeldung.isnumeric;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.apache.commons.lang3.math.NumberUtils;
|
||||
import org.junit.Test;
|
||||
|
||||
public class NumberUtilsIsCreatableUnitTest {
|
||||
@Test
|
||||
public void givenApacheCommons_whenUsingIsParsable_thenTrue() {
|
||||
// Valid Numbers
|
||||
assertThat(NumberUtils.isCreatable("22")).isTrue();
|
||||
assertThat(NumberUtils.isCreatable("5.05")).isTrue();
|
||||
assertThat(NumberUtils.isCreatable("-200")).isTrue();
|
||||
assertThat(NumberUtils.isCreatable("10.0d")).isTrue();
|
||||
assertThat(NumberUtils.isCreatable("1000L")).isTrue();
|
||||
assertThat(NumberUtils.isCreatable("0xFF")).isTrue();
|
||||
assertThat(NumberUtils.isCreatable("07")).isTrue();
|
||||
assertThat(NumberUtils.isCreatable("2.99e+8")).isTrue();
|
||||
|
||||
// Invalid Numbers
|
||||
assertThat(NumberUtils.isCreatable(null)).isFalse();
|
||||
assertThat(NumberUtils.isCreatable("")).isFalse();
|
||||
assertThat(NumberUtils.isCreatable("abc")).isFalse();
|
||||
assertThat(NumberUtils.isCreatable(" 22 ")).isFalse();
|
||||
assertThat(NumberUtils.isCreatable("09")).isFalse();
|
||||
}
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package com.baeldung.isnumeric;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.apache.commons.lang3.math.NumberUtils;
|
||||
import org.junit.Test;
|
||||
|
||||
public class NumberUtilsIsParsableUnitTest {
|
||||
@Test
|
||||
public void givenApacheCommons_whenUsingIsParsable_thenTrue() {
|
||||
// Valid Numbers
|
||||
assertThat(NumberUtils.isParsable("22")).isTrue();
|
||||
assertThat(NumberUtils.isParsable("-23")).isTrue();
|
||||
assertThat(NumberUtils.isParsable("2.2")).isTrue();
|
||||
assertThat(NumberUtils.isParsable("09")).isTrue();
|
||||
|
||||
// Invalid Numbers
|
||||
assertThat(NumberUtils.isParsable(null)).isFalse();
|
||||
assertThat(NumberUtils.isParsable("")).isFalse();
|
||||
assertThat(NumberUtils.isParsable("6.2f")).isFalse();
|
||||
assertThat(NumberUtils.isParsable("9.8d")).isFalse();
|
||||
assertThat(NumberUtils.isParsable("22L")).isFalse();
|
||||
assertThat(NumberUtils.isParsable("0xFF")).isFalse();
|
||||
assertThat(NumberUtils.isParsable("2.99e+8")).isFalse();
|
||||
}
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
package com.baeldung.isnumeric;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class RegularExpressionsUnitTest {
|
||||
public static boolean isNumeric(String strNum) {
|
||||
return strNum.matches("-?\\d+(\\.\\d+)?");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingRegularExpressions_thenTrue() {
|
||||
// Valid Numbers
|
||||
assertThat(isNumeric("22")).isTrue();
|
||||
assertThat(isNumeric("5.05")).isTrue();
|
||||
assertThat(isNumeric("-200")).isTrue();
|
||||
|
||||
// Invalid Numbers
|
||||
assertThat(isNumeric("abc")).isFalse();
|
||||
}
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package com.baeldung.isnumeric;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.junit.Test;
|
||||
|
||||
public class StringUtilsIsNumericSpaceUnitTest {
|
||||
@Test
|
||||
public void givenApacheCommons_whenUsingIsNumericSpace_thenTrue() {
|
||||
// Valid Numbers
|
||||
assertThat(StringUtils.isNumericSpace("123")).isTrue();
|
||||
assertThat(StringUtils.isNumericSpace("١٢٣")).isTrue();
|
||||
assertThat(StringUtils.isNumericSpace("")).isTrue();
|
||||
assertThat(StringUtils.isNumericSpace(" ")).isTrue();
|
||||
assertThat(StringUtils.isNumericSpace("12 3")).isTrue();
|
||||
|
||||
// Invalid Numbers
|
||||
assertThat(StringUtils.isNumericSpace(null)).isFalse();
|
||||
assertThat(StringUtils.isNumericSpace("ab2c")).isFalse();
|
||||
assertThat(StringUtils.isNumericSpace("12.3")).isFalse();
|
||||
assertThat(StringUtils.isNumericSpace("-123")).isFalse();
|
||||
}
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package com.baeldung.isnumeric;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.junit.Test;
|
||||
|
||||
public class StringUtilsIsNumericUnitTest {
|
||||
@Test
|
||||
public void givenApacheCommons_whenUsingIsNumeric_thenTrue() {
|
||||
// Valid Numbers
|
||||
assertThat(StringUtils.isNumeric("123")).isTrue();
|
||||
assertThat(StringUtils.isNumeric("١٢٣")).isTrue();
|
||||
assertThat(StringUtils.isNumeric("१२३")).isTrue();
|
||||
|
||||
// Invalid Numbers
|
||||
assertThat(StringUtils.isNumeric(null)).isFalse();
|
||||
assertThat(StringUtils.isNumeric("")).isFalse();
|
||||
assertThat(StringUtils.isNumeric(" ")).isFalse();
|
||||
assertThat(StringUtils.isNumeric("12 3")).isFalse();
|
||||
assertThat(StringUtils.isNumeric("ab2c")).isFalse();
|
||||
assertThat(StringUtils.isNumeric("12.3")).isFalse();
|
||||
assertThat(StringUtils.isNumeric("-123")).isFalse();
|
||||
}
|
||||
}
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
package com.baeldung.split;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import com.google.common.base.Splitter;
|
||||
|
||||
public class SplitUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenString_whenSplit_thenReturnsArray_through_JavaLangString() {
|
||||
assertThat("peter,james,thomas".split(",")).containsExactly("peter", "james", "thomas");
|
||||
|
||||
assertThat("car jeep scooter".split(" ")).containsExactly("car", "jeep", "scooter");
|
||||
|
||||
assertThat("1-120-232323".split("-")).containsExactly("1", "120", "232323");
|
||||
|
||||
assertThat("192.168.1.178".split("\\.")).containsExactly("192", "168", "1", "178");
|
||||
|
||||
assertThat("b a, e, l.d u, n g".split("\\s+|,\\s*|\\.\\s*")).containsExactly("b", "a", "e", "l", "d", "u", "n", "g");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenSplit_thenReturnsArray_through_StringUtils() {
|
||||
StringUtils.split("car jeep scooter");
|
||||
|
||||
assertThat(StringUtils.split("car jeep scooter")).containsExactly("car", "jeep", "scooter");
|
||||
|
||||
assertThat(StringUtils.split("car jeep scooter")).containsExactly("car", "jeep", "scooter");
|
||||
|
||||
assertThat(StringUtils.split("car:jeep:scooter", ":")).containsExactly("car", "jeep", "scooter");
|
||||
|
||||
assertThat(StringUtils.split("car.jeep.scooter", ".")).containsExactly("car", "jeep", "scooter");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenSplit_thenReturnsList_Splitter() {
|
||||
// given
|
||||
List<String> resultList = Splitter.on(',')
|
||||
.trimResults()
|
||||
.omitEmptyStrings()
|
||||
.splitToList("car,jeep,, scooter");
|
||||
|
||||
assertThat(resultList).containsExactly("car", "jeep", "scooter");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStringContainsSpaces_whenSplitAndTrim_thenReturnsArray_using_Regex() {
|
||||
assertThat(" car , jeep, scooter ".trim()
|
||||
.split("\\s*,\\s*")).containsExactly("car", "jeep", "scooter");
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStringContainsSpaces_whenSplitAndTrim_thenReturnsArray_using_java_8() {
|
||||
assertThat(Arrays.stream(" car , jeep, scooter ".split(","))
|
||||
.map(String::trim)
|
||||
.toArray(String[]::new)).containsExactly("car", "jeep", "scooter");
|
||||
}
|
||||
}
|
||||
+83
@@ -0,0 +1,83 @@
|
||||
package com.baeldung.streamoperations;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class JoinerSplitterUnitTest {
|
||||
|
||||
@Test
|
||||
public void provided_array_convert_to_stream_and_convert_to_string() {
|
||||
|
||||
String[] programming_languages = {"java", "python", "nodejs", "ruby"};
|
||||
|
||||
String expectation = "java,python,nodejs,ruby";
|
||||
|
||||
String result = JoinerSplitter.join(programming_languages);
|
||||
assertEquals(result, expectation);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArray_transformedToStream_convertToPrefixPostfixString() {
|
||||
|
||||
String[] programming_languages = {"java", "python",
|
||||
"nodejs", "ruby"};
|
||||
String expectation = "[java,python,nodejs,ruby]";
|
||||
|
||||
String result = JoinerSplitter.joinWithPrefixPostFix(programming_languages);
|
||||
assertEquals(result, expectation);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_transformedToStream_convertToList() {
|
||||
|
||||
String programming_languages = "java,python,nodejs,ruby";
|
||||
|
||||
List<String> expectation = new ArrayList<String>();
|
||||
expectation.add("java");
|
||||
expectation.add("python");
|
||||
expectation.add("nodejs");
|
||||
expectation.add("ruby");
|
||||
|
||||
List<String> result = JoinerSplitter.split(programming_languages);
|
||||
|
||||
assertEquals(result, expectation);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_transformedToStream_convertToListOfChar() {
|
||||
|
||||
String programming_languages = "java,python,nodejs,ruby";
|
||||
|
||||
List<Character> expectation = new ArrayList<Character>();
|
||||
char[] charArray = programming_languages.toCharArray();
|
||||
for (char c : charArray) {
|
||||
expectation.add(c);
|
||||
}
|
||||
|
||||
List<Character> result = JoinerSplitter.splitToListOfChar(programming_languages);
|
||||
assertEquals(result, expectation);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStringArray_transformedToStream_convertToMap() {
|
||||
|
||||
String[] programming_languages = new String[] {"language:java","os:linux","editor:emacs"};
|
||||
|
||||
Map<String,String> expectation=new HashMap<>();
|
||||
expectation.put("language", "java");
|
||||
expectation.put("os", "linux");
|
||||
expectation.put("editor", "emacs");
|
||||
|
||||
Map<String, String> result = JoinerSplitter.arrayToMap(programming_languages);
|
||||
assertEquals(result, expectation);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
+153
@@ -0,0 +1,153 @@
|
||||
package com.baeldung.stringcomparison;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.junit.Test;
|
||||
|
||||
public class StringComparisonUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenUsingComparisonOperator_ThenComparingStrings() {
|
||||
|
||||
String string1 = "using comparison operator";
|
||||
String string2 = "using comparison operator";
|
||||
String string3 = new String("using comparison operator");
|
||||
|
||||
assertThat(string1 == string2).isTrue();
|
||||
assertThat(string1 == string3).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingEqualsMethod_ThenComparingStrings() {
|
||||
|
||||
String string1 = "using equals method";
|
||||
String string2 = "using equals method";
|
||||
|
||||
String string3 = "using EQUALS method";
|
||||
String string4 = new String("using equals method");
|
||||
|
||||
assertThat(string1.equals(string2)).isTrue();
|
||||
assertThat(string1.equals(string4)).isTrue();
|
||||
|
||||
assertThat(string1.equals(null)).isFalse();
|
||||
assertThat(string1.equals(string3)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingEqualsIgnoreCase_ThenComparingStrings() {
|
||||
|
||||
String string1 = "using equals ignore case";
|
||||
String string2 = "USING EQUALS IGNORE CASE";
|
||||
|
||||
assertThat(string1.equalsIgnoreCase(string2)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingCompareTo_ThenComparingStrings() {
|
||||
|
||||
String author = "author";
|
||||
String book = "book";
|
||||
String duplicateBook = "book";
|
||||
|
||||
assertThat(author.compareTo(book)).isEqualTo(-1);
|
||||
assertThat(book.compareTo(author)).isEqualTo(1);
|
||||
assertThat(duplicateBook.compareTo(book)).isEqualTo(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingCompareToIgnoreCase_ThenComparingStrings() {
|
||||
|
||||
String author = "Author";
|
||||
String book = "book";
|
||||
String duplicateBook = "BOOK";
|
||||
|
||||
assertThat(author.compareToIgnoreCase(book)).isEqualTo(-1);
|
||||
assertThat(book.compareToIgnoreCase(author)).isEqualTo(1);
|
||||
assertThat(duplicateBook.compareToIgnoreCase(book)).isEqualTo(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingObjectsEqualsMethod_ThenComparingStrings() {
|
||||
|
||||
String string1 = "using objects equals";
|
||||
String string2 = "using objects equals";
|
||||
String string3 = new String("using objects equals");
|
||||
|
||||
assertThat(Objects.equals(string1, string2)).isTrue();
|
||||
assertThat(Objects.equals(string1, string3)).isTrue();
|
||||
|
||||
assertThat(Objects.equals(null, null)).isTrue();
|
||||
assertThat(Objects.equals(null, string1)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingEqualsOfApacheCommons_ThenComparingStrings() {
|
||||
|
||||
assertThat(StringUtils.equals(null, null)).isTrue();
|
||||
assertThat(StringUtils.equals(null, "equals method")).isFalse();
|
||||
assertThat(StringUtils.equals("equals method", "equals method")).isTrue();
|
||||
assertThat(StringUtils.equals("equals method", "EQUALS METHOD")).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingEqualsIgnoreCaseOfApacheCommons_ThenComparingStrings() {
|
||||
|
||||
assertThat(StringUtils.equalsIgnoreCase(null, null)).isTrue();
|
||||
assertThat(StringUtils.equalsIgnoreCase(null, "equals method")).isFalse();
|
||||
assertThat(StringUtils.equalsIgnoreCase("equals method", "equals method")).isTrue();
|
||||
assertThat(StringUtils.equalsIgnoreCase("equals method", "EQUALS METHOD")).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingEqualsAnyOf_ThenComparingStrings() {
|
||||
|
||||
assertThat(StringUtils.equalsAny(null, null, null)).isTrue();
|
||||
assertThat(StringUtils.equalsAny("equals any", "equals any", "any")).isTrue();
|
||||
assertThat(StringUtils.equalsAny("equals any", null, "equals any")).isTrue();
|
||||
assertThat(StringUtils.equalsAny(null, "equals", "any")).isFalse();
|
||||
assertThat(StringUtils.equalsAny("equals any", "EQUALS ANY", "ANY")).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingEqualsAnyIgnoreCase_ThenComparingStrings() {
|
||||
|
||||
assertThat(StringUtils.equalsAnyIgnoreCase(null, null, null)).isTrue();
|
||||
assertThat(StringUtils.equalsAnyIgnoreCase("equals any", "equals any", "any")).isTrue();
|
||||
assertThat(StringUtils.equalsAnyIgnoreCase("equals any", null, "equals any")).isTrue();
|
||||
assertThat(StringUtils.equalsAnyIgnoreCase(null, "equals", "any")).isFalse();
|
||||
assertThat(StringUtils.equalsAnyIgnoreCase("equals any ignore case", "EQUALS ANY IGNORE CASE", "any")).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingCompare_thenComparingStringsWithNulls() {
|
||||
|
||||
assertThat(StringUtils.compare(null, null)).isEqualTo(0);
|
||||
assertThat(StringUtils.compare(null, "abc")).isEqualTo(-1);
|
||||
|
||||
assertThat(StringUtils.compare("abc", "bbc")).isEqualTo(-1);
|
||||
assertThat(StringUtils.compare("bbc", "abc")).isEqualTo(1);
|
||||
assertThat(StringUtils.compare("abc", "abc")).isEqualTo(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingCompareIgnoreCase_ThenComparingStringsWithNulls() {
|
||||
|
||||
assertThat(StringUtils.compareIgnoreCase(null, null)).isEqualTo(0);
|
||||
assertThat(StringUtils.compareIgnoreCase(null, "abc")).isEqualTo(-1);
|
||||
|
||||
assertThat(StringUtils.compareIgnoreCase("Abc", "bbc")).isEqualTo(-1);
|
||||
assertThat(StringUtils.compareIgnoreCase("bbc", "ABC")).isEqualTo(1);
|
||||
assertThat(StringUtils.compareIgnoreCase("abc", "ABC")).isEqualTo(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingCompareWithNullIsLessOption_ThenComparingStrings() {
|
||||
|
||||
assertThat(StringUtils.compare(null, "abc", true)).isEqualTo(-1);
|
||||
assertThat(StringUtils.compare(null, "abc", false)).isEqualTo(1);
|
||||
}
|
||||
|
||||
}
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
package com.baeldung.substring;
|
||||
|
||||
import java.util.Scanner;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class SubstringUnitTest {
|
||||
|
||||
String text = "Julia Evans was born on 25-09-1984. She is currently living in the USA (United States of America).";
|
||||
|
||||
@Test
|
||||
public void givenAString_whenUsedStringUtils_ShouldReturnProperSubstring() {
|
||||
Assert.assertEquals("United States of America", StringUtils.substringBetween(text, "(", ")"));
|
||||
Assert.assertEquals("the USA (United States of America).", StringUtils.substringAfter(text, "living in "));
|
||||
Assert.assertEquals("Julia Evans", StringUtils.substringBefore(text, " was born"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAString_whenUsedScanner_ShouldReturnProperSubstring() {
|
||||
try (Scanner scanner = new Scanner(text)) {
|
||||
scanner.useDelimiter("\\.");
|
||||
Assert.assertEquals("Julia Evans was born on 25-09-1984", scanner.next());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAString_whenUsedSplit_ShouldReturnProperSubstring() {
|
||||
String[] sentences = text.split("\\.");
|
||||
Assert.assertEquals("Julia Evans was born on 25-09-1984", sentences[0]);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAString_whenUsedRegex_ShouldReturnProperSubstring() {
|
||||
Pattern pattern = Pattern.compile("\\d{2}\\-\\d{2}-\\d{4}");
|
||||
Matcher matcher = pattern.matcher(text);
|
||||
|
||||
if (matcher.find()) {
|
||||
Assert.assertEquals("25-09-1984", matcher.group());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAString_whenUsedSubSequence_ShouldReturnProperSubstring() {
|
||||
Assert.assertEquals("USA (United States of America)", text.subSequence(67, text.length() - 1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAString_whenUsedSubstring_ShouldReturnProperSubstring() {
|
||||
Assert.assertEquals("USA (United States of America).", text.substring(67));
|
||||
Assert.assertEquals("USA (United States of America)", text.substring(67, text.length() - 1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAString_whenUsedSubstringWithIndexOf_ShouldReturnProperSubstring() {
|
||||
Assert.assertEquals("United States of America", text.substring(text.indexOf('(') + 1, text.indexOf(')')));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAString_whenUsedSubstringWithLastIndexOf_ShouldReturnProperSubstring() {
|
||||
Assert.assertEquals("1984", text.substring(text.lastIndexOf('-') + 1, text.indexOf('.')));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAString_whenUsedSubstringWithIndexOfAString_ShouldReturnProperSubstring() {
|
||||
Assert.assertEquals("USA (United States of America)", text.substring(text.indexOf("USA"), text.indexOf(')') + 1));
|
||||
}
|
||||
|
||||
}
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
package com.baeldung.substringsearch;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* BAEL-2832: Different ways to check if a Substring could be found in a String.
|
||||
*/
|
||||
public class SubstringSearchUnitTest {
|
||||
|
||||
@Test
|
||||
public void searchSubstringWithIndexOf() {
|
||||
Assert.assertEquals(9, "Bohemian Rhapsodyan".indexOf("Rhap"));
|
||||
|
||||
// indexOf will return -1, because it's case sensitive
|
||||
Assert.assertEquals(-1, "Bohemian Rhapsodyan".indexOf("rhap"));
|
||||
|
||||
// indexOf will return 9, because it's all lowercase
|
||||
Assert.assertEquals(9, "Bohemian Rhapsodyan".toLowerCase()
|
||||
.indexOf("rhap"));
|
||||
|
||||
// it will return 6, because it's the first occurrence. Sorry Queen for being blasphemic
|
||||
Assert.assertEquals(6, "Bohemian Rhapsodyan".indexOf("an"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void searchSubstringWithContains() {
|
||||
Assert.assertTrue("Hey Ho, let's go".contains("Hey"));
|
||||
|
||||
// contains will return false, because it's case sensitive
|
||||
Assert.assertFalse("Hey Ho, let's go".contains("hey"));
|
||||
|
||||
// contains will return true, because it's all lowercase
|
||||
Assert.assertTrue("Hey Ho, let's go".toLowerCase().contains("hey"));
|
||||
|
||||
// contains will return false, because 'jey' can't be found
|
||||
Assert.assertFalse("Hey Ho, let's go".contains("jey"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void searchSubstringWithStringUtils() {
|
||||
Assert.assertTrue(StringUtils.containsIgnoreCase("Runaway train", "train"));
|
||||
|
||||
// it will also be true, because ignores case ;)
|
||||
Assert.assertTrue(StringUtils.containsIgnoreCase("Runaway train", "Train"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void searchUsingPattern() {
|
||||
|
||||
// We create the Pattern first
|
||||
Pattern pattern = Pattern.compile("(?<!\\S)" + "road" + "(?!\\S)");
|
||||
|
||||
// We need to create the Matcher after
|
||||
Matcher matcher = pattern.matcher("Hit the road Jack");
|
||||
|
||||
// find will return true when the first match is found
|
||||
Assert.assertTrue(matcher.find());
|
||||
|
||||
// We will create a different matcher with a different text
|
||||
matcher = pattern.matcher("and don't you come back no more");
|
||||
|
||||
// find will return false, because 'road' can't be find as a substring
|
||||
Assert.assertFalse(matcher.find());
|
||||
}
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package com.baeldung.tostring;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class CustomerArrayToStringUnitTest {
|
||||
private static final String CUSTOMER_ARRAY_TO_STRING = "Customer [orders=[Order [orderId=A1111, desc=Game, value=0]], getFirstName()=Rajesh, getLastName()=Bhojwani]";
|
||||
|
||||
@Test
|
||||
public void givenArray_whenToString_thenCustomerDetails() {
|
||||
CustomerArrayToString customer = new CustomerArrayToString();
|
||||
customer.setFirstName("Rajesh");
|
||||
customer.setLastName("Bhojwani");
|
||||
Order[] orders = new Order[1];
|
||||
orders[0] = new Order();
|
||||
orders[0].setOrderId("A1111");
|
||||
orders[0].setDesc("Game");
|
||||
orders[0].setStatus("In-Shiping");
|
||||
customer.setOrders(orders);
|
||||
|
||||
assertEquals(CUSTOMER_ARRAY_TO_STRING, customer.toString());
|
||||
}
|
||||
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package com.baeldung.tostring;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class CustomerComplexObjectToStringUnitTest {
|
||||
private static final String CUSTOMER_COMPLEX_TO_STRING = "Customer [order=Order [orderId=A1111, desc=Game, value=0], getFirstName()=Rajesh, getLastName()=Bhojwani]";
|
||||
|
||||
@Test
|
||||
public void givenComplex_whenToString_thenCustomerDetails() {
|
||||
CustomerComplexObjectToString customer = new CustomerComplexObjectToString();
|
||||
customer.setFirstName("Rajesh");
|
||||
customer.setLastName("Bhojwani");
|
||||
Order order = new Order();
|
||||
order.setOrderId("A1111");
|
||||
order.setDesc("Game");
|
||||
order.setStatus("In-Shiping");
|
||||
customer.setOrder(order);
|
||||
|
||||
assertEquals(CUSTOMER_COMPLEX_TO_STRING, customer.toString());
|
||||
}
|
||||
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
package com.baeldung.tostring;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class CustomerPrimitiveToStringUnitTest {
|
||||
|
||||
private static final String CUSTOMER_PRIMITIVE_TO_STRING = "Customer [balance=110, getFirstName()=Rajesh, getLastName()=Bhojwani]";
|
||||
|
||||
@Test
|
||||
public void givenPrimitive_whenToString_thenCustomerDetails() {
|
||||
CustomerPrimitiveToString customer = new CustomerPrimitiveToString();
|
||||
customer.setFirstName("Rajesh");
|
||||
customer.setLastName("Bhojwani");
|
||||
customer.setBalance(110);
|
||||
|
||||
assertEquals(CUSTOMER_PRIMITIVE_TO_STRING, customer.toString());
|
||||
}
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
package com.baeldung.tostring;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class CustomerWrapperCollectionToStringUnitTest {
|
||||
private static final String CUSTOMER_WRAPPER_COLLECTION_TO_STRING = "Customer [score=8, orders=[Book, Pen], fullname=Bhojwani, Rajesh, getFirstName()=Rajesh, getLastName()=Bhojwani]";
|
||||
|
||||
@Test
|
||||
public void givenWrapperCollectionStrBuffer_whenToString_thenCustomerDetails() {
|
||||
CustomerWrapperCollectionToString customer = new CustomerWrapperCollectionToString();
|
||||
customer.setFirstName("Rajesh");
|
||||
customer.setLastName("Bhojwani");
|
||||
customer.setScore(8);
|
||||
|
||||
List<String> orders = new ArrayList<String>();
|
||||
orders.add("Book");
|
||||
orders.add("Pen");
|
||||
customer.setOrders(orders);
|
||||
|
||||
StringBuffer fullname = new StringBuffer();
|
||||
fullname.append(customer.getLastName() + ", " + customer.getFirstName());
|
||||
customer.setFullname(fullname);
|
||||
|
||||
assertEquals(CUSTOMER_WRAPPER_COLLECTION_TO_STRING, customer.toString());
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user