Merge branch 'master' into BAEL-5146-Validate-Serialization

This commit is contained in:
Amitabh Tiwari
2021-10-24 07:05:06 +05:30
63 changed files with 1775 additions and 29 deletions

View File

@@ -0,0 +1,3 @@
### Relevant articles:
- [Pattern Matching for Switch](https://www.baeldung.com/java-switch-pattern-matching)

View File

@@ -0,0 +1,81 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-17</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-17</name>
<packaging>jar</packaging>
<url>http://maven.apache.org</url>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../../</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<release>${maven.compiler.release}</release>
<compilerArgs>--enable-preview</compilerArgs>
<source>${maven.compiler.source.version}</source>
<target>${maven.compiler.target.version}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${surefire.plugin.version}</version>
<configuration>
<argLine>--enable-preview</argLine>
<forkCount>1</forkCount>
</configuration>
<dependencies>
<dependency>
<groupId>org.apache.maven.surefire</groupId>
<artifactId>surefire-api</artifactId>
<version>${surefire.plugin.version}</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
<properties>
<maven.compiler.source.version>17</maven.compiler.source.version>
<maven.compiler.target.version>17</maven.compiler.target.version>
<maven.compiler.release>17</maven.compiler.release>
<maven-compiler-plugin.version>3.8.1</maven-compiler-plugin.version>
<surefire.plugin.version>3.0.0-M5</surefire.plugin.version>
<assertj.version>3.17.2</assertj.version>
</properties>
</project>

View File

@@ -0,0 +1,25 @@
package com.baeldung.switchpatterns;
public class GuardedPatterns {
static double getDoubleValueUsingIf(Object o) {
return switch (o) {
case String s -> {
if (s.length() > 0) {
yield Double.parseDouble(s);
} else {
yield 0d;
}
}
default -> 0d;
};
}
static double getDoubleValueUsingGuardedPatterns(Object o) {
return switch (o) {
case String s && s.length() > 0 -> Double.parseDouble(s);
default -> 0d;
};
}
}

View File

@@ -0,0 +1,20 @@
package com.baeldung.switchpatterns;
public class HandlingNullValues {
static double getDoubleUsingSwitchNullCase(Object o) {
return switch (o) {
case String s -> Double.parseDouble(s);
case null -> 0d;
default -> 0d;
};
}
static double getDoubleUsingSwitchTotalType(Object o) {
return switch (o) {
case String s -> Double.parseDouble(s);
case Object ob -> 0d;
};
}
}

View File

@@ -0,0 +1,29 @@
package com.baeldung.switchpatterns;
public class ParenthesizedPatterns {
static double getDoubleValueUsingIf(Object o) {
return switch (o) {
case String s -> {
if (s.length() > 0) {
if (s.contains("#") || s.contains("@")) {
yield 0d;
} else {
yield Double.parseDouble(s);
}
} else {
yield 0d;
}
}
default -> 0d;
};
}
static double getDoubleValueUsingParenthesizedPatterns(Object o) {
return switch (o) {
case String s && s.length() > 0 && !(s.contains("#") || s.contains("@")) -> Double.parseDouble(s);
default -> 0d;
};
}
}

View File

@@ -0,0 +1,14 @@
package com.baeldung.switchpatterns;
public class PatternMatching {
public static void main(String[] args) {
Object o = args[0];
if (o instanceof String s) {
System.out.printf("Object is a string %s", s);
} else if(o instanceof Number n) {
System.out.printf("Object is a number %n", n);
}
}
}

View File

@@ -0,0 +1,14 @@
package com.baeldung.switchpatterns;
public class SwitchStatement {
public static void main(String[] args) {
final String b = "B";
switch (args[0]) {
case "A" -> System.out.println("Parameter is A");
case b -> System.out.println("Parameter is b");
default -> System.out.println("Parameter is unknown");
};
}
}

View File

@@ -0,0 +1,30 @@
package com.baeldung.switchpatterns;
public class TypePatterns {
static double getDoubleUsingIf(Object o) {
double result;
if (o instanceof Integer) {
result = ((Integer) o).doubleValue();
} else if (o instanceof Float) {
result = ((Float) o).doubleValue();
} else if (o instanceof String) {
result = Double.parseDouble(((String) o));
} else {
result = 0d;
}
return result;
}
static double getDoubleUsingSwitch(Object o) {
return switch (o) {
case Integer i -> i.doubleValue();
case Float f -> f.doubleValue();
case String s -> Double.parseDouble(s);
default -> 0d;
};
}
}

View File

@@ -0,0 +1,30 @@
package com.baeldung.switchpatterns;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static com.baeldung.switchpatterns.GuardedPatterns.*;
class GuardedPatternsUnitTest {
@Test
void givenIfImplementation_whenUsingEmptyString_thenDoubleIsReturned() {
assertEquals(0d, getDoubleValueUsingIf(""));
}
@Test
void givenIfImplementation_whenUsingNonEmptyString_thenDoubleIsReturned() {
assertEquals(10d, getDoubleValueUsingIf("10"));
}
@Test
void givenPatternsImplementation_whenUsingEmptyString_thenDoubleIsReturned() {
assertEquals(0d, getDoubleValueUsingGuardedPatterns(""));
}
@Test
void givenPatternsImplementation_whenUsingNonEmptyString_thenDoubleIsReturned() {
assertEquals(10d, getDoubleValueUsingGuardedPatterns("10"));
}
}

View File

@@ -0,0 +1,30 @@
package com.baeldung.switchpatterns;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static com.baeldung.switchpatterns.HandlingNullValues.*;
class HandlingNullValuesUnitTest {
@Test
void givenNullCaseInSwitch_whenUsingStringAsArgument_thenDoubleIsReturned() {
assertEquals(10d, getDoubleUsingSwitchNullCase("10"));
}
@Test
void givenTotalTypeInSwitch_whenUsingNullArgument_thenDoubleIsReturned() {
assertEquals(0d, getDoubleUsingSwitchNullCase(null));
}
@Test
void givenTotalTypeInSwitch_whenUsingStringAsArgument_thenDoubleIsReturned() {
assertEquals(10d, getDoubleUsingSwitchTotalType("10"));
}
@Test
void givenNullCaseInSwitch_whenUsingNullArgument_thenDoubleIsReturned() {
assertEquals(0d, getDoubleUsingSwitchTotalType(null));
}
}

View File

@@ -0,0 +1,40 @@
package com.baeldung.switchpatterns;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static com.baeldung.switchpatterns.ParenthesizedPatterns.*;
class ParenthesizedPatternsUnitTest {
@Test
void givenIfImplementation_whenUsingEmptyString_thenDoubleIsReturned() {
assertEquals(0d, getDoubleValueUsingIf(""));
}
@Test
void givenIfImplementation_whenUsingNonEmptyString_thenDoubleIsReturned() {
assertEquals(10d, getDoubleValueUsingIf("10"));
}
@Test
void givenIfImplementation_whenStringContainsSpecialChar_thenDoubleIsReturned() {
assertEquals(0d, getDoubleValueUsingIf("@10"));
}
@Test
void givenPatternsImplementation_whenUsingEmptyString_thenDoubleIsReturned() {
assertEquals(0d, getDoubleValueUsingParenthesizedPatterns(""));
}
@Test
void givenPatternsImplementation_whenUsingNonEmptyString_thenDoubleIsReturned() {
assertEquals(10d, getDoubleValueUsingParenthesizedPatterns("10"));
}
@Test
void givenPatternsImplementation_whenStringContainsSpecialChar_thenDoubleIsReturned() {
assertEquals(0d, getDoubleValueUsingParenthesizedPatterns("@10"));
}
}

View File

@@ -0,0 +1,49 @@
package com.baeldung.switchpatterns;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static com.baeldung.switchpatterns.TypePatterns.*;
class TypePatternsUnitTest {
@Test
void givenIfImplementation_whenUsingIntegerAsArgument_thenDoubleIsReturned() {
assertEquals(10d, getDoubleUsingIf(10));
}
@Test
void givenIfImplementation_whenUsingDoubleAsArgument_thenDoubleIsReturned() {
assertEquals(10d, getDoubleUsingIf(10.0f));
}
@Test
void givenIfImplementation_whenUsingStringAsArgument_thenDoubleIsReturned() {
assertEquals(10d, getDoubleUsingIf("10"));
}
@Test
void givenIfImplementation_whenUsingCharAsArgument_thenDoubleIsReturned() {
assertEquals(0d, getDoubleUsingIf('c'));
}
@Test
void givenSwitchImplementation_whenUsingIntegerAsArgument_thenDoubleIsReturned() {
assertEquals(10d, getDoubleUsingSwitch(10));
}
@Test
void givenSwitchImplementation_whenUsingDoubleAsArgument_thenDoubleIsReturned() {
assertEquals(10d, getDoubleUsingSwitch(10.0f));
}
@Test
void givenSwitchImplementation_whenUsingStringAsArgument_thenDoubleIsReturned() {
assertEquals(10d, getDoubleUsingSwitch("10"));
}
@Test
void givenSwitchImplementation_whenUsingCharAsArgument_thenDoubleIsReturned() {
assertEquals(0d, getDoubleUsingSwitch('c'));
}
}

View File

@@ -5,3 +5,4 @@ This module contains articles about arrays conversion in Java
## Relevant Articles
- [Convert a Float to a Byte Array in Java](https://www.baeldung.com/java-convert-float-to-byte-array)
- [Converting Between Stream and Array in Java](https://www.baeldung.com/java-stream-to-array)
- [Convert a Byte Array to a Numeric Representation in Java](https://www.baeldung.com/java-byte-array-to-number)

View File

@@ -19,6 +19,11 @@
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
</dependencies>
<properties>

View File

@@ -0,0 +1,281 @@
package com.baeldung.array.conversions;
import com.google.common.primitives.Ints;
import com.google.common.primitives.Longs;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.Conversion;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.util.Arrays;
class ByteArrayToNumericRepresentation {
static int convertByteArrayToIntUsingShiftOperator(byte[] bytes) {
int value = 0;
for (byte b : bytes) {
value = (value << 8) + (b & 0xFF);
}
return value;
}
static byte[] convertIntToByteArrayUsingShiftOperator(int value) {
byte[] bytes = new byte[Integer.BYTES];
int length = bytes.length;
for (int i = 0; i < length; i++) {
bytes[length - i - 1] = (byte) (value & 0xFF);
value >>= 8;
}
return bytes;
}
static long convertByteArrayToLongUsingShiftOperator(byte[] bytes) {
long value = 0;
for (byte b : bytes) {
value <<= 8;
value |= (b & 0xFF);
}
return value;
}
static byte[] convertLongToByteArrayUsingShiftOperator(long value) {
byte[] bytes = new byte[Long.BYTES];
int length = bytes.length;
for (int i = 0; i < length; i++) {
bytes[length - i - 1] = (byte) (value & 0xFF);
value >>= 8;
}
return bytes;
}
static float convertByteArrayToFloatUsingShiftOperator(byte[] bytes) {
// convert bytes to int
int intValue = 0;
for (byte b : bytes) {
intValue = (intValue << 8) + (b & 0xFF);
}
// convert int to float
return Float.intBitsToFloat(intValue);
}
static byte[] convertFloatToByteArrayUsingShiftOperator(float value) {
// convert float to int
int intValue = Float.floatToIntBits(value);
// convert int to bytes
byte[] bytes = new byte[Float.BYTES];
int length = bytes.length;
for (int i = 0; i < length; i++) {
bytes[length - i - 1] = (byte) (intValue & 0xFF);
intValue >>= 8;
}
return bytes;
}
static double convertingByteArrayToDoubleUsingShiftOperator(byte[] bytes) {
long longValue = 0;
for (byte b : bytes) {
longValue = (longValue << 8) + (b & 0xFF);
}
return Double.longBitsToDouble(longValue);
}
static byte[] convertDoubleToByteArrayUsingShiftOperator(double value) {
long longValue = Double.doubleToLongBits(value);
byte[] bytes = new byte[Double.BYTES];
int length = bytes.length;
for (int i = 0; i < length; i++) {
bytes[length - i - 1] = (byte) (longValue & 0xFF);
longValue >>= 8;
}
return bytes;
}
static int convertByteArrayToIntUsingByteBuffer(byte[] bytes) {
ByteBuffer buffer = ByteBuffer.allocate(Integer.BYTES);
buffer.put(bytes);
buffer.rewind();
return buffer.getInt();
}
static byte[] convertIntToByteArrayUsingByteBuffer(int value) {
ByteBuffer buffer = ByteBuffer.allocate(Integer.BYTES);
buffer.putInt(value);
buffer.rewind();
return buffer.array();
}
static long convertByteArrayToLongUsingByteBuffer(byte[] bytes) {
ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES);
buffer.put(bytes);
buffer.rewind();
return buffer.getLong();
}
static byte[] convertLongToByteArrayUsingByteBuffer(long value) {
ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES);
buffer.putLong(value);
buffer.rewind();
return buffer.array();
}
static float convertByteArrayToFloatUsingByteBuffer(byte[] bytes) {
ByteBuffer buffer = ByteBuffer.allocate(Float.BYTES);
buffer.put(bytes);
buffer.rewind();
return buffer.getFloat();
}
static byte[] convertFloatToByteArrayUsingByteBuffer(float value) {
ByteBuffer buffer = ByteBuffer.allocate(Float.BYTES);
buffer.putFloat(value);
buffer.rewind();
return buffer.array();
}
static double convertByteArrayToDoubleUsingByteBuffer(byte[] bytes) {
ByteBuffer buffer = ByteBuffer.allocate(Double.BYTES);
buffer.put(bytes);
buffer.rewind();
return buffer.getDouble();
}
static byte[] convertDoubleToByteArrayUsingByteBuffer(double value) {
ByteBuffer buffer = ByteBuffer.allocate(Double.BYTES);
buffer.putDouble(value);
buffer.rewind();
return buffer.array();
}
static int convertByteArrayToIntUsingBigInteger(byte[] bytes) {
return new BigInteger(bytes).intValue();
}
static byte[] convertIntToByteArrayUsingBigInteger(int value) {
return BigInteger.valueOf(value).toByteArray();
}
static long convertByteArrayToLongUsingBigInteger(byte[] bytes) {
return new BigInteger(bytes).longValue();
}
static byte[] convertLongToByteArrayUsingBigInteger(long value) {
return BigInteger.valueOf(value).toByteArray();
}
static float convertByteArrayToFloatUsingBigInteger(byte[] bytes) {
int intValue = new BigInteger(bytes).intValue();
return Float.intBitsToFloat(intValue);
}
static byte[] convertFloatToByteArrayUsingBigInteger(float value) {
int intValue = Float.floatToIntBits(value);
return BigInteger.valueOf(intValue).toByteArray();
}
static double convertByteArrayToDoubleUsingBigInteger(byte[] bytes) {
long longValue = new BigInteger(bytes).longValue();
return Double.longBitsToDouble(longValue);
}
static byte[] convertDoubleToByteArrayUsingBigInteger(double value) {
long longValue = Double.doubleToLongBits(value);
return BigInteger.valueOf(longValue).toByteArray();
}
static int convertingByteArrayToIntUsingGuava(byte[] bytes) {
return Ints.fromByteArray(bytes);
}
static byte[] convertIntToByteArrayUsingGuava(int value) {
return Ints.toByteArray(value);
}
static long convertByteArrayToLongUsingGuava(byte[] bytes) {
return Longs.fromByteArray(bytes);
}
static byte[] convertLongToByteArrayUsingGuava(long value) {
return Longs.toByteArray(value);
}
static float convertByteArrayToFloatUsingGuava(byte[] bytes) {
int intValue = Ints.fromByteArray(bytes);
return Float.intBitsToFloat(intValue);
}
static byte[] convertFloatToByteArrayUsingGuava(float value) {
int intValue = Float.floatToIntBits(value);
return Ints.toByteArray(intValue);
}
static double convertByteArrayToDoubleUsingGuava(byte[] bytes) {
long longValue = Longs.fromByteArray(bytes);
return Double.longBitsToDouble(longValue);
}
static byte[] convertDoubleToByteArrayUsingGuava(double value) {
long longValue = Double.doubleToLongBits(value);
return Longs.toByteArray(longValue);
}
static int convertByteArrayToIntUsingCommonsLang(byte[] bytes) {
byte[] copyBytes = Arrays.copyOf(bytes, bytes.length);
ArrayUtils.reverse(copyBytes);
return Conversion.byteArrayToInt(copyBytes, 0, 0, 0, copyBytes.length);
}
static byte[] convertIntToByteArrayUsingCommonsLang(int value) {
byte[] bytes = new byte[Integer.BYTES];
Conversion.intToByteArray(value, 0, bytes, 0, bytes.length);
ArrayUtils.reverse(bytes);
return bytes;
}
static long convertByteArrayToLongUsingCommonsLang(byte[] bytes) {
byte[] copyBytes = Arrays.copyOf(bytes, bytes.length);
ArrayUtils.reverse(copyBytes);
return Conversion.byteArrayToLong(copyBytes, 0, 0, 0, copyBytes.length);
}
static byte[] convertLongToByteArrayUsingCommonsLang(long value) {
byte[] bytes = new byte[Long.BYTES];
Conversion.longToByteArray(value, 0, bytes, 0, bytes.length);
ArrayUtils.reverse(bytes);
return bytes;
}
static float convertByteArrayToFloatUsingCommonsLang(byte[] bytes) {
byte[] copyBytes = Arrays.copyOf(bytes, bytes.length);
ArrayUtils.reverse(copyBytes);
int intValue = Conversion.byteArrayToInt(copyBytes, 0, 0, 0, copyBytes.length);
return Float.intBitsToFloat(intValue);
}
static byte[] convertFloatToByteArrayUsingCommonsLang(float value) {
int intValue = Float.floatToIntBits(value);
byte[] bytes = new byte[Float.BYTES];
Conversion.intToByteArray(intValue, 0, bytes, 0, bytes.length);
ArrayUtils.reverse(bytes);
return bytes;
}
static double convertByteArrayToDoubleUsingCommonsLang(byte[] bytes) {
byte[] copyBytes = Arrays.copyOf(bytes, bytes.length);
ArrayUtils.reverse(copyBytes);
long longValue = Conversion.byteArrayToLong(copyBytes, 0, 0, 0, copyBytes.length);
return Double.longBitsToDouble(longValue);
}
static byte[] convertDoubleToByteArrayUsingCommonsLang(double value) {
long longValue = Double.doubleToLongBits(value);
byte[] bytes = new byte[Long.BYTES];
Conversion.longToByteArray(longValue, 0, bytes, 0, bytes.length);
ArrayUtils.reverse(bytes);
return bytes;
}
}

View File

@@ -0,0 +1,316 @@
package com.baeldung.array.conversions;
import org.junit.Test;
import static com.baeldung.array.conversions.ByteArrayToNumericRepresentation.*;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
public class ByteArrayToNumericRepresentationUnitTest {
private static final byte[] INT_BYTE_ARRAY = new byte[]{
(byte) 0xCA, (byte) 0xFE, (byte) 0xBA, (byte) 0xBE
};
private static final int INT_VALUE = 0xCAFEBABE;
private static final byte[] FLOAT_BYTE_ARRAY = new byte[]{
(byte) 0x40, (byte) 0x48, (byte) 0xF5, (byte) 0xC3
};
private static final float FLOAT_VALUE = 3.14F;
private static final byte[] LONG_BYTE_ARRAY = new byte[]{
(byte) 0x01, (byte) 0x23, (byte) 0x45, (byte) 0x67,
(byte) 0x89, (byte) 0xAB, (byte) 0xCD, (byte) 0xEF
};
private static final long LONG_VALUE = 0x0123456789ABCDEFL;
private static final byte[] DOUBLE_BYTE_ARRAY = new byte[]{
(byte) 0x3F, (byte) 0xE3, (byte) 0xC6, (byte) 0xA7,
(byte) 0xEF, (byte) 0x9D, (byte) 0xB2, (byte) 0x2D
};
private static final double DOUBLE_VALUE = 0.618D;
@Test
public void givenShiftOperator_whenConvertingByteArrayToInt_thenSuccess() {
int value = convertByteArrayToIntUsingShiftOperator(INT_BYTE_ARRAY);
assertEquals(INT_VALUE, value);
}
@Test
public void givenShiftOperator_whenConvertingIntToByteArray_thenSuccess() {
byte[] bytes = convertIntToByteArrayUsingShiftOperator(INT_VALUE);
assertArrayEquals(INT_BYTE_ARRAY, bytes);
}
@Test
public void givenShiftOperator_whenConvertingByteArrayToLong_thenSuccess() {
long value = convertByteArrayToLongUsingShiftOperator(LONG_BYTE_ARRAY);
assertEquals(LONG_VALUE, value);
}
@Test
public void givenShiftOperator_whenConvertingLongToByteArray_thenSuccess() {
byte[] bytes = convertLongToByteArrayUsingShiftOperator(LONG_VALUE);
assertArrayEquals(LONG_BYTE_ARRAY, bytes);
}
@Test
public void givenShiftOperator_whenConvertingByteArrayToFloat_thenSuccess() {
float value = convertByteArrayToFloatUsingShiftOperator(FLOAT_BYTE_ARRAY);
assertEquals(Float.floatToIntBits(FLOAT_VALUE), Float.floatToIntBits(value));
}
@Test
public void givenShiftOperator_whenConvertingFloatToByteArray_thenSuccess() {
byte[] bytes = convertFloatToByteArrayUsingShiftOperator(FLOAT_VALUE);
assertArrayEquals(FLOAT_BYTE_ARRAY, bytes);
}
@Test
public void givenShiftOperator_whenConvertingByteArrayToDouble_thenSuccess() {
double value = convertingByteArrayToDoubleUsingShiftOperator(DOUBLE_BYTE_ARRAY);
assertEquals(Double.doubleToLongBits(DOUBLE_VALUE), Double.doubleToLongBits(value));
}
@Test
public void givenShiftOperator_whenConvertingDoubleToByteArray_thenSuccess() {
byte[] bytes = convertDoubleToByteArrayUsingShiftOperator(DOUBLE_VALUE);
assertArrayEquals(DOUBLE_BYTE_ARRAY, bytes);
}
@Test
public void givenByteBuffer_whenConvertingByteArrayToInt_thenSuccess() {
int value = convertByteArrayToIntUsingByteBuffer(INT_BYTE_ARRAY);
assertEquals(INT_VALUE, value);
}
@Test
public void givenByteBuffer_whenConvertingIntToByteArray_thenSuccess() {
byte[] bytes = convertIntToByteArrayUsingByteBuffer(INT_VALUE);
assertArrayEquals(INT_BYTE_ARRAY, bytes);
}
@Test
public void givenByteBuffer_whenConvertingByteArrayToLong_thenSuccess() {
long value = convertByteArrayToLongUsingByteBuffer(LONG_BYTE_ARRAY);
assertEquals(LONG_VALUE, value);
}
@Test
public void givenByteBuffer_whenConvertingLongToByteArray_thenSuccess() {
byte[] bytes = convertLongToByteArrayUsingByteBuffer(LONG_VALUE);
assertArrayEquals(LONG_BYTE_ARRAY, bytes);
}
@Test
public void givenByteBuffer_whenConvertingByteArrayToFloat_thenSuccess() {
float value = convertByteArrayToFloatUsingByteBuffer(FLOAT_BYTE_ARRAY);
assertEquals(Float.floatToIntBits(FLOAT_VALUE), Float.floatToIntBits(value));
}
@Test
public void givenByteBuffer_whenConvertingFloatToByteArray_thenSuccess() {
byte[] bytes = convertFloatToByteArrayUsingByteBuffer(FLOAT_VALUE);
assertArrayEquals(FLOAT_BYTE_ARRAY, bytes);
}
@Test
public void givenByteBuffer_whenConvertingByteArrayToDouble_thenSuccess() {
double value = convertByteArrayToDoubleUsingByteBuffer(DOUBLE_BYTE_ARRAY);
assertEquals(Double.doubleToLongBits(DOUBLE_VALUE), Double.doubleToLongBits(value));
}
@Test
public void givenByteBuffer_whenConvertingDoubleToByteArray_thenSuccess() {
byte[] bytes = convertDoubleToByteArrayUsingByteBuffer(DOUBLE_VALUE);
assertArrayEquals(DOUBLE_BYTE_ARRAY, bytes);
}
@Test
public void givenBigInteger_whenConvertingByteArrayToInt_thenSuccess() {
int value = convertByteArrayToIntUsingBigInteger(INT_BYTE_ARRAY);
assertEquals(INT_VALUE, value);
}
@Test
public void givenBigInteger_whenConvertingIntToByteArray_thenSuccess() {
byte[] bytes = convertIntToByteArrayUsingBigInteger(INT_VALUE);
assertArrayEquals(INT_BYTE_ARRAY, bytes);
}
@Test
public void givenBigInteger_whenConvertingByteArrayToLong_thenSuccess() {
long value = convertByteArrayToLongUsingBigInteger(LONG_BYTE_ARRAY);
assertEquals(LONG_VALUE, value);
}
@Test
public void givenBigInteger_whenConvertingLongToByteArray_thenSuccess() {
byte[] bytes = convertLongToByteArrayUsingBigInteger(LONG_VALUE);
assertArrayEquals(LONG_BYTE_ARRAY, bytes);
}
@Test
public void givenBigInteger_whenConvertingByteArrayToFloat_thenSuccess() {
float value = convertByteArrayToFloatUsingBigInteger(FLOAT_BYTE_ARRAY);
assertEquals(Float.floatToIntBits(FLOAT_VALUE), Float.floatToIntBits(value));
}
@Test
public void givenBigInteger_whenConvertingFloatToByteArray_thenSuccess() {
byte[] bytes = convertFloatToByteArrayUsingBigInteger(FLOAT_VALUE);
assertArrayEquals(FLOAT_BYTE_ARRAY, bytes);
}
@Test
public void givenBigInteger_whenConvertingByteArrayToDouble_thenSuccess() {
double value = convertByteArrayToDoubleUsingBigInteger(DOUBLE_BYTE_ARRAY);
assertEquals(Double.doubleToLongBits(DOUBLE_VALUE), Double.doubleToLongBits(value));
}
@Test
public void givenBigInteger_whenConvertingDoubleToByteArray_thenSuccess() {
byte[] bytes = convertDoubleToByteArrayUsingBigInteger(DOUBLE_VALUE);
assertArrayEquals(DOUBLE_BYTE_ARRAY, bytes);
}
@Test
public void givenGuava_whenConvertingByteArrayToInt_thenSuccess() {
int value = convertingByteArrayToIntUsingGuava(INT_BYTE_ARRAY);
assertEquals(INT_VALUE, value);
}
@Test
public void givenGuava_whenConvertingIntToByteArray_thenSuccess() {
byte[] bytes = convertIntToByteArrayUsingGuava(INT_VALUE);
assertArrayEquals(INT_BYTE_ARRAY, bytes);
}
@Test
public void givenGuava_whenConvertingByteArrayToLong_thenSuccess() {
long value = convertByteArrayToLongUsingGuava(LONG_BYTE_ARRAY);
assertEquals(LONG_VALUE, value);
}
@Test
public void givenGuava_whenConvertingLongToByteArray_thenSuccess() {
byte[] bytes = convertLongToByteArrayUsingGuava(LONG_VALUE);
assertArrayEquals(LONG_BYTE_ARRAY, bytes);
}
@Test
public void givenGuava_whenConvertingByteArrayToFloat_thenSuccess() {
float value = convertByteArrayToFloatUsingGuava(FLOAT_BYTE_ARRAY);
assertEquals(Float.floatToIntBits(FLOAT_VALUE), Float.floatToIntBits(value));
}
@Test
public void givenGuava_whenConvertingFloatToByteArray_thenSuccess() {
byte[] bytes = convertFloatToByteArrayUsingGuava(FLOAT_VALUE);
assertArrayEquals(FLOAT_BYTE_ARRAY, bytes);
}
@Test
public void givenGuava_whenConvertingByteArrayToDouble_thenSuccess() {
double value = convertByteArrayToDoubleUsingGuava(DOUBLE_BYTE_ARRAY);
assertEquals(Double.doubleToLongBits(DOUBLE_VALUE), Double.doubleToLongBits(value));
}
@Test
public void givenGuava_whenConvertingDoubleToByteArray_thenSuccess() {
byte[] bytes = convertDoubleToByteArrayUsingGuava(DOUBLE_VALUE);
assertArrayEquals(DOUBLE_BYTE_ARRAY, bytes);
}
@Test
public void givenCommonsLang_whenConvertingByteArrayToInt_thenSuccess() {
int value = convertByteArrayToIntUsingCommonsLang(INT_BYTE_ARRAY);
assertEquals(INT_VALUE, value);
}
@Test
public void givenCommonsLang_whenConvertingIntToByteArray_thenSuccess() {
byte[] bytes = convertIntToByteArrayUsingCommonsLang(INT_VALUE);
assertArrayEquals(INT_BYTE_ARRAY, bytes);
}
@Test
public void givenCommonsLang_whenConvertingByteArrayToLong_thenSuccess() {
long value = convertByteArrayToLongUsingCommonsLang(LONG_BYTE_ARRAY);
assertEquals(LONG_VALUE, value);
}
@Test
public void givenCommonsLang_whenConvertingLongToByteArray_thenSuccess() {
byte[] bytes = convertLongToByteArrayUsingCommonsLang(LONG_VALUE);
assertArrayEquals(LONG_BYTE_ARRAY, bytes);
}
@Test
public void givenCommonsLang_whenConvertingByteArrayToFloat_thenSuccess() {
float value = convertByteArrayToFloatUsingCommonsLang(FLOAT_BYTE_ARRAY);
assertEquals(Float.floatToIntBits(FLOAT_VALUE), Float.floatToIntBits(value));
}
@Test
public void givenCommonsLang_whenConvertingFloatToByteArray_thenSuccess() {
byte[] bytes = convertFloatToByteArrayUsingCommonsLang(FLOAT_VALUE);
assertArrayEquals(FLOAT_BYTE_ARRAY, bytes);
}
@Test
public void givenCommonsLang_whenConvertingByteArrayToDouble_thenSuccess() {
double value = convertByteArrayToDoubleUsingCommonsLang(DOUBLE_BYTE_ARRAY);
assertEquals(Double.doubleToLongBits(DOUBLE_VALUE), Double.doubleToLongBits(value));
}
@Test
public void givenCommonsLang_whenConvertingDoubleToByteArray_thenSuccess() {
byte[] bytes = convertDoubleToByteArrayUsingCommonsLang(DOUBLE_VALUE);
assertArrayEquals(DOUBLE_BYTE_ARRAY, bytes);
}
}

View File

@@ -6,3 +6,4 @@
- [Split a String in Java and Keep the Delimiters](https://www.baeldung.com/java-split-string-keep-delimiters)
- [Validate String as Filename in Java](https://www.baeldung.com/java-validate-filename)
- [Count Spaces in a Java String](https://www.baeldung.com/java-string-count-spaces)
- [Remove Accents and Diacritics From a String in Java](https://www.baeldung.com/java-remove-accents-from-text)

View File

@@ -0,0 +1,49 @@
package com.baeldung.accentsanddiacriticsremoval;
import org.apache.commons.lang3.StringUtils;
import java.text.Normalizer;
import java.util.StringJoiner;
class StringNormalizer {
static String removeAccentsWithApacheCommons(String input) {
return StringUtils.stripAccents(input);
}
static String removeAccents(String input) {
return normalize(input).replaceAll("\\p{M}", "");
}
static String unicodeValueOfNormalizedString(String input) {
return toUnicode(normalize(input));
}
private static String normalize(String input) {
return input == null ? null : Normalizer.normalize(input, Normalizer.Form.NFKD);
}
private static String toUnicode(String input) {
if (input.length() == 1) {
return toUnicode(input.charAt(0));
} else {
StringJoiner stringJoiner = new StringJoiner(" ");
for (char c : input.toCharArray()) {
stringJoiner.add(toUnicode(c));
}
return stringJoiner.toString();
}
}
private static String toUnicode(char input) {
String hex = Integer.toHexString(input);
StringBuilder sb = new StringBuilder(hex);
while (sb.length() < 4) {
sb.insert(0, "0");
}
sb.insert(0, "\\u");
return sb.toString();
}
}

View File

@@ -0,0 +1,37 @@
package com.baeldung.doublequotesremoval;
import com.google.common.base.CharMatcher;
public class DoubleQuotesRemovalUtils {
public static String removeWithSubString(String input) {
if (input != null && input.length() >= 2 && input.charAt(0) == '\"'
&& input.charAt(input.length() - 1) == '\"') {
return input.substring(1, input.length() - 1);
}
return input;
}
public static String removeWithReplaceAllSimple(String input) {
if (input == null || input.isEmpty())
return input;
return input.replaceAll("\"", "");
}
public static String removeWithReplaceAllAdvanced(String input) {
if (input == null || input.isEmpty())
return input;
return input.replaceAll("^\"|\"$", "");
}
public static String removeWithGuava(String input) {
if (input == null || input.isEmpty())
return input;
return CharMatcher.is('\"').trimFrom(input);
}
}

View File

@@ -0,0 +1,70 @@
package com.baeldung.accentsanddiacriticsremoval;
import org.junit.Test;
import org.openjdk.jmh.annotations.Setup;
import java.text.Collator;
import static java.lang.Character.*;
import static java.lang.String.valueOf;
import static org.junit.Assert.assertEquals;
public class CollatorUnitTest {
private final Collator collator = Collator.getInstance();
@Setup
public void setup() {
collator.setDecomposition(2);
}
@Test
public void givenAccentedStringAndPrimaryCollatorStrength_whenCompareWithASCIIString_thenReturnTrue() {
Collator collator = Collator.getInstance();
collator.setDecomposition(2);
collator.setStrength(0);
assertEquals(0, collator.compare("a", "a"));
assertEquals(0, collator.compare("ä", "a"));
assertEquals(0, collator.compare("A", "a"));
assertEquals(1, collator.compare("b", "a"));
assertEquals(0, collator.compare(valueOf(toChars(0x0001)), valueOf(toChars(0x0002))));
}
@Test
public void givenAccentedStringAndSecondaryCollatorStrength_whenCompareWithASCIIString_thenReturnTrue() {
collator.setStrength(1);
assertEquals(1, collator.compare("ä", "a"));
assertEquals(1, collator.compare("b", "a"));
assertEquals(0, collator.compare("A", "a"));
assertEquals(0, collator.compare("a", "a"));
assertEquals(0, collator.compare(valueOf(toChars(0x0001)), valueOf(toChars(0x0002))));
}
@Test
public void givenAccentedStringAndTeriaryCollatorStrength_whenCompareWithASCIIString_thenReturnTrue() {
collator.setStrength(2);
assertEquals(1, collator.compare("A", "a"));
assertEquals(1, collator.compare("ä", "a"));
assertEquals(1, collator.compare("b", "a"));
assertEquals(0, collator.compare("a", "a"));
assertEquals(0, collator.compare(valueOf(toChars(0x0001)), valueOf(toChars(0x0002))));
}
@Test
public void givenAccentedStringAndIdenticalCollatorStrength_whenCompareWithASCIIString_thenReturnTrue() {
collator.setStrength(3);
assertEquals(1, collator.compare("A", "a"));
assertEquals(1, collator.compare("ä", "a"));
assertEquals(1, collator.compare("b", "a"));
assertEquals(-1, collator.compare(valueOf(toChars(0x0001)), valueOf(toChars(0x0002))));
assertEquals(0, collator.compare("a", "a"));
}
@Test
public void givenNondecomposableAccentedStringAndIdenticalCollatorStrength_whenCompareWithASCIIString_thenReturnTrue() {
collator.setStrength(0);
assertEquals(1, collator.compare("ł", "l"));
assertEquals(1, collator.compare("ø", "o"));
}
}

View File

@@ -0,0 +1,51 @@
package com.baeldung.accentsanddiacriticsremoval;
import static org.junit.Assert.assertFalse;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.text.Normalizer;
import org.junit.jupiter.api.Test;
class StringNormalizerUnitTest {
@Test
public void givenNotNormalizedString_whenIsNormalized_thenReturnFalse() {
assertFalse(Normalizer.isNormalized("āăąēîïĩíĝġńñšŝśûůŷ", Normalizer.Form.NFKD));
}
@Test
void givenStringWithDecomposableUnicodeCharacters_whenRemoveAccents_thenReturnASCIIString() {
assertEquals("aaaeiiiiggnnsssuuy", StringNormalizer.removeAccents("āăąēîïĩíĝġńñšŝśûůŷ"));
}
@Test
void givenStringWithDecomposableUnicodeCharacters_whenRemoveAccentsWithApacheCommons_thenReturnASCIIString() {
assertEquals("aaaeiiiiggnnsssuuy", StringNormalizer.removeAccentsWithApacheCommons("āăąēîïĩíĝġńñšŝśûůŷ"));
}
@Test
void givenStringWithNondecomposableUnicodeCharacters_whenRemoveAccents_thenReturnOriginalString() {
assertEquals("łđħœ", StringNormalizer.removeAccents("łđħœ"));
}
@Test
void givenStringWithNondecomposableUnicodeCharacters_whenRemoveAccentsWithApacheCommons_thenReturnModifiedString() {
assertEquals("lđħœ", StringNormalizer.removeAccentsWithApacheCommons("łđħœ"));
}
@Test
void givenStringWithDecomposableUnicodeCharacters_whenUnicodeValueOfNormalizedString_thenReturnUnicodeValue() {
assertEquals("\\u0066 \\u0069", StringNormalizer.unicodeValueOfNormalizedString(""));
assertEquals("\\u0061 \\u0304", StringNormalizer.unicodeValueOfNormalizedString("ā"));
assertEquals("\\u0069 \\u0308", StringNormalizer.unicodeValueOfNormalizedString("ï"));
assertEquals("\\u006e \\u0301", StringNormalizer.unicodeValueOfNormalizedString("ń"));
}
@Test
void givenStringWithNonDecomposableUnicodeCharacters_whenUnicodeValueOfNormalizedString_thenReturnOriginalValue() {
assertEquals("\\u0142", StringNormalizer.unicodeValueOfNormalizedString("ł"));
assertEquals("\\u0127", StringNormalizer.unicodeValueOfNormalizedString("ħ"));
assertEquals("\\u0111", StringNormalizer.unicodeValueOfNormalizedString("đ"));
}
}

View File

@@ -0,0 +1,42 @@
package com.baeldung.doublequotesremoval;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.junit.jupiter.api.Test;
public class DoubleQuotesRemovalUtilsUnitTest {
@Test
public void given_EmptyString_ShouldReturn_EmptyString() {
String input = "";
assertTrue(DoubleQuotesRemovalUtils.removeWithSubString(input).isEmpty());
assertTrue(DoubleQuotesRemovalUtils.removeWithReplaceAllSimple(input).isEmpty());
assertTrue(DoubleQuotesRemovalUtils.removeWithReplaceAllAdvanced(input).isEmpty());
assertTrue(DoubleQuotesRemovalUtils.removeWithGuava(input).isEmpty());
}
@Test
public void given_DoubleQuotesOnly_ShouldReturn_EmptyString() {
String input = "\"\"";
assertTrue(DoubleQuotesRemovalUtils.removeWithSubString(input).isEmpty());
assertTrue(DoubleQuotesRemovalUtils.removeWithReplaceAllSimple(input).isEmpty());
assertTrue(DoubleQuotesRemovalUtils.removeWithReplaceAllAdvanced(input).isEmpty());
assertTrue(DoubleQuotesRemovalUtils.removeWithGuava(input).isEmpty());
}
@Test
public void given_TextWithDoubleQuotes_ShouldReturn_TextOnly() {
String input = "\"Example of text for this test suit\"";
String expectedResult = "Example of text for this test suit";
assertEquals(expectedResult, DoubleQuotesRemovalUtils.removeWithSubString(input));
assertEquals(expectedResult, DoubleQuotesRemovalUtils.removeWithReplaceAllSimple(input));
assertEquals(expectedResult, DoubleQuotesRemovalUtils.removeWithReplaceAllAdvanced(input));
assertEquals(expectedResult, DoubleQuotesRemovalUtils.removeWithGuava(input));
}
}