Move articles out of java-strings part4
This commit is contained in:
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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]));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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() + "]";
|
||||
}
|
||||
}
|
||||
@@ -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() + "]";
|
||||
}
|
||||
}
|
||||
@@ -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() + "]";
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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() + "]";
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
@@ -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