Merge remote-tracking branch 'upstream/master'
This commit is contained in:
@@ -5,3 +5,4 @@
|
||||
- [Collecting Stream Elements into a List in Java](https://www.baeldung.com/java-stream-to-list-collecting)
|
||||
- [New Features in Java 16](https://www.baeldung.com/java-16-new-features)
|
||||
- [Guide to Java 8 groupingBy Collector](https://www.baeldung.com/java-groupingby-collector)
|
||||
- [Value-Based Classes in Java](https://www.baeldung.com/java-value-based-classes)
|
||||
|
||||
@@ -1,2 +1,3 @@
|
||||
## Relevant Articles
|
||||
- [Sequenced Collections in Java 21](https://www.baeldung.com/java-21-sequenced-collections)
|
||||
- [String Templates in Java 21](https://www.baeldung.com/java-21-string-templates)
|
||||
|
||||
@@ -12,23 +12,36 @@
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<!-- <build>-->
|
||||
<!-- <plugins>-->
|
||||
<!-- <plugin>-->
|
||||
<!-- <groupId>org.apache.maven.plugins</groupId>-->
|
||||
<!-- <artifactId>maven-compiler-plugin</artifactId>-->
|
||||
<!-- <configuration>-->
|
||||
<!-- <source>{maven.compiler.source.version}</source>-->
|
||||
<!-- <target>{maven.compiler.target.version}</target>-->
|
||||
<!-- </configuration>-->
|
||||
<!-- </plugin>-->
|
||||
<!-- </plugins>-->
|
||||
<!-- </build>-->
|
||||
<properties>
|
||||
<maven.compiler.source.version>21</maven.compiler.source.version>
|
||||
<maven.compiler.target.version>21</maven.compiler.target.version>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
</properties>
|
||||
|
||||
<!-- <properties>-->
|
||||
<!-- <maven.compiler.source.version>21</maven.compiler.source.version>-->
|
||||
<!-- <maven.compiler.target.version>21</maven.compiler.target.version>-->
|
||||
<!-- <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>-->
|
||||
<!-- </properties>-->
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<configuration>
|
||||
<source>21</source>
|
||||
<target>21</target>
|
||||
<!-- Needed due to a bug with JDK 21, described here: https://issues.apache.org/jira/browse/MCOMPILER-546?page=com.atlassian.jira.plugin.system.issuetabpanels%3Acomment-tabpanel&focusedCommentId=17767513 -->
|
||||
<debug>false</debug>
|
||||
<compilerArgs>
|
||||
<arg>--enable-preview</arg>
|
||||
</compilerArgs>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<configuration>
|
||||
<argLine>--enable-preview</argLine>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
</project>
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
package com.baeldung.stringtemplates;
|
||||
|
||||
import java.text.MessageFormat;
|
||||
|
||||
public class StringCompositionTechniques {
|
||||
String composeUsingPlus(String feelsLike, String temperature, String unit) {
|
||||
return "Today's weather is " + feelsLike + ", with a temperature of " + temperature + " degrees " + unit;
|
||||
}
|
||||
|
||||
String composeUsingStringBuffer(String feelsLike, String temperature, String unit) {
|
||||
return new StringBuffer().append("Today's weather is ")
|
||||
.append(feelsLike)
|
||||
.append(", with a temperature of ")
|
||||
.append(temperature)
|
||||
.append(" degrees ")
|
||||
.append(unit)
|
||||
.toString();
|
||||
}
|
||||
|
||||
String composeUsingStringBuilder(String feelsLike, String temperature, String unit) {
|
||||
return new StringBuilder().append("Today's weather is ")
|
||||
.append(feelsLike)
|
||||
.append(", with a temperature of ")
|
||||
.append(temperature)
|
||||
.append(" degrees ")
|
||||
.append(unit)
|
||||
.toString();
|
||||
}
|
||||
|
||||
String composeUsingFormatters(String feelsLike, String temperature, String unit) {
|
||||
return String.format("Today's weather is %s, with a temperature of %s degrees %s", feelsLike, temperature, unit);
|
||||
}
|
||||
|
||||
String composeUsingMessageFormatter(String feelsLike, String temperature, String unit) {
|
||||
return MessageFormat.format("Today''s weather is {0}, with a temperature of {1} degrees {2}", feelsLike, temperature, unit);
|
||||
}
|
||||
}
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
package com.baeldung.stringtemplates;
|
||||
|
||||
import static java.lang.StringTemplate.RAW;
|
||||
import static java.util.FormatProcessor.FMT;
|
||||
|
||||
public class StringTemplateExamples {
|
||||
String interpolationUsingSTRProcessor(String feelsLike, String temperature, String unit) {
|
||||
return STR
|
||||
. "Today's weather is \{ feelsLike }, with a temperature of \{ temperature } degrees \{ unit }" ;
|
||||
}
|
||||
|
||||
String interpolationOfJSONBlock(String feelsLike, String temperature, String unit) {
|
||||
return STR
|
||||
. """
|
||||
{
|
||||
"feelsLike": "\{ feelsLike }",
|
||||
"temperature": "\{ temperature }",
|
||||
"unit": "\{ unit }"
|
||||
}
|
||||
""" ;
|
||||
}
|
||||
|
||||
String interpolationWithExpressions() {
|
||||
return STR
|
||||
. "Today's weather is \{ getFeelsLike() }, with a temperature of \{ getTemperature() } degrees \{ getUnit() }" ;
|
||||
}
|
||||
|
||||
String interpolationWithTemplates() {
|
||||
StringTemplate str = RAW
|
||||
. "Today's weather is \{ getFeelsLike() }, with a temperature of \{ getTemperature() } degrees \{ getUnit() }" ;
|
||||
return STR.process(str);
|
||||
}
|
||||
|
||||
String interpolationOfJSONBlockWithFMT(String feelsLike, float temperature, String unit) {
|
||||
return FMT
|
||||
. """
|
||||
{
|
||||
"feelsLike": "%1s\{ feelsLike }",
|
||||
"temperature": "%2.2f\{ temperature }",
|
||||
"unit": "%1s\{ unit }"
|
||||
}
|
||||
""" ;
|
||||
}
|
||||
|
||||
private String getFeelsLike() {
|
||||
return "pleasant";
|
||||
}
|
||||
|
||||
private String getTemperature() {
|
||||
return "25";
|
||||
}
|
||||
|
||||
private String getUnit() {
|
||||
return "Celsius";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.baeldung.unnamed.variables;
|
||||
|
||||
public record Car<T extends Engine>(String name, String color, T engine) { }
|
||||
|
||||
abstract class Engine { }
|
||||
|
||||
class GasEngine extends Engine { }
|
||||
|
||||
class ElectricEngine extends Engine { }
|
||||
|
||||
class HybridEngine extends Engine { }
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
package com.baeldung.unnamed.variables;
|
||||
|
||||
public class UnnamedPatterns {
|
||||
|
||||
static String getObjectsColorWithNamedPattern(Object object) {
|
||||
if (object instanceof Car(String name, String color, Engine engine)) {
|
||||
return color;
|
||||
}
|
||||
return "No color!";
|
||||
}
|
||||
|
||||
static String getObjectsColorWithUnnamedPattern(Object object) {
|
||||
if (object instanceof Car(_, String color, _)) {
|
||||
return color;
|
||||
}
|
||||
return "No color!";
|
||||
}
|
||||
|
||||
static String getObjectsColorWithSwitchAndNamedPattern(Object object) {
|
||||
return switch (object) {
|
||||
case Car(String name, String color, Engine engine) -> color;
|
||||
default -> "No color!";
|
||||
};
|
||||
}
|
||||
|
||||
static String getObjectsColorWithSwitchAndUnnamedPattern(Object object) {
|
||||
return switch (object) {
|
||||
case Car(_, String color, _) -> color;
|
||||
default -> "No color!";
|
||||
};
|
||||
}
|
||||
|
||||
static String getEngineTypeWithNamedPattern(Car<?> car) {
|
||||
return switch (car) {
|
||||
case Car(String name, String color, GasEngine engine) -> "gas";
|
||||
case Car(String name, String color, ElectricEngine engine) -> "electric";
|
||||
case Car(String name, String color, HybridEngine engine) -> "hybrid";
|
||||
default -> "none";
|
||||
};
|
||||
}
|
||||
|
||||
static String getEngineTypeWithUnnamedPattern(Car<?> car) {
|
||||
return switch (car) {
|
||||
case Car(_, _, GasEngine _) -> "gas";
|
||||
case Car(_, _, ElectricEngine _) -> "electric";
|
||||
case Car(_, _, HybridEngine _) -> "hybrid";
|
||||
default -> "none";
|
||||
};
|
||||
}
|
||||
}
|
||||
+134
@@ -0,0 +1,134 @@
|
||||
package com.baeldung.unnamed.variables;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Queue;
|
||||
|
||||
class Transaction implements AutoCloseable {
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
System.out.println("Closed!");
|
||||
}
|
||||
}
|
||||
|
||||
public class UnnamedVariables {
|
||||
|
||||
static int countCarsOverLimitWithNamedVariable(Collection<Car<?>> cars, int limit) {
|
||||
var total = 0;
|
||||
var totalOverLimit = 0;
|
||||
for (var car : cars) {
|
||||
total++;
|
||||
if (total > limit) {
|
||||
totalOverLimit++;
|
||||
// side effect
|
||||
}
|
||||
}
|
||||
return totalOverLimit;
|
||||
}
|
||||
|
||||
static int countCarsOverLimitWithUnnamedVariable(Collection<Car<?>> cars, int limit) {
|
||||
var total = 0;
|
||||
var totalOverLimit = 0;
|
||||
for (var _ : cars) {
|
||||
total++;
|
||||
if (total > limit) {
|
||||
totalOverLimit++;
|
||||
// side effect
|
||||
}
|
||||
}
|
||||
return totalOverLimit;
|
||||
}
|
||||
|
||||
static void sendNotificationToCarsWithNamedVariable(Collection<Car<?>> cars) {
|
||||
sendOneTimeNotification();
|
||||
for (int i = 0; i < cars.size(); i++) {
|
||||
// Notify car
|
||||
}
|
||||
}
|
||||
|
||||
static void sendNotificationToCarsWithUnnamedVariable(Collection<Car<?>> cars) {
|
||||
for (int i = 0, _ = sendOneTimeNotification(); i < cars.size(); i++) {
|
||||
// Notify car
|
||||
}
|
||||
}
|
||||
|
||||
private static int sendOneTimeNotification() {
|
||||
System.out.println("Sending one time notification!");
|
||||
return 1;
|
||||
}
|
||||
|
||||
static Car<?> removeThreeCarsAndReturnFirstRemovedWithNamedVariables(Queue<Car<?>> cars) {
|
||||
var x = cars.poll();
|
||||
var y = cars.poll();
|
||||
var z = cars.poll();
|
||||
return x;
|
||||
}
|
||||
|
||||
static Car<?> removeThreeCarsAndReturnFirstRemovedWithUnnamedVariables(Queue<Car<?>> cars) {
|
||||
var car = cars.poll();
|
||||
var _ = cars.poll();
|
||||
var _ = cars.poll();
|
||||
return car;
|
||||
}
|
||||
|
||||
static void handleCarExceptionWithNamedVariables(Car<?> car) {
|
||||
try {
|
||||
someOperationThatFails(car);
|
||||
} catch (IllegalStateException ex) {
|
||||
System.out.println("Got an illegal state exception for: " + car.name());
|
||||
} catch (RuntimeException ex) {
|
||||
System.out.println("Got a runtime exception!");
|
||||
}
|
||||
}
|
||||
|
||||
static void handleCarExceptionWithUnnamedVariables(Car<?> car) {
|
||||
try {
|
||||
someOperationThatFails(car);
|
||||
} catch (IllegalStateException | NumberFormatException _) {
|
||||
System.out.println("Got an illegal state exception for: " + car.name());
|
||||
} catch (RuntimeException _) {
|
||||
System.out.println("Got a runtime exception!");
|
||||
}
|
||||
}
|
||||
|
||||
static void obtainTransactionAndUpdateCarWithNamedVariables(Car<?> car) {
|
||||
try (var transaction = new Transaction()) {
|
||||
updateCar(car);
|
||||
}
|
||||
}
|
||||
|
||||
static void obtainTransactionAndUpdateCarWithUnnamedVariables(Car<?> car) {
|
||||
try (var _ = new Transaction()) {
|
||||
updateCar(car);
|
||||
}
|
||||
}
|
||||
|
||||
static void updateCar(Car<?> car) {
|
||||
// Some update logic
|
||||
System.out.println("Car updated!");
|
||||
}
|
||||
|
||||
static Map<String, List<Car<?>>> getCarsByFirstLetterWithNamedVariables(List<Car<?>> cars) {
|
||||
Map<String, List<Car<?>>> carMap = new HashMap<>();
|
||||
cars.forEach(car ->
|
||||
carMap.computeIfAbsent(car.name().substring(0, 1), firstLetter -> new ArrayList<>()).add(car)
|
||||
);
|
||||
return carMap;
|
||||
}
|
||||
|
||||
static Map<String, List<Car<?>>> getCarsByFirstLetterWithUnnamedVariables(List<Car<?>> cars) {
|
||||
Map<String, List<Car<?>>> carMap = new HashMap<>();
|
||||
cars.forEach(car ->
|
||||
carMap.computeIfAbsent(car.name().substring(0, 1), _ -> new ArrayList<>()).add(car)
|
||||
);
|
||||
return carMap;
|
||||
}
|
||||
|
||||
private static void someOperationThatFails(Car<?> car) {
|
||||
throw new IllegalStateException("Triggered exception for: " + car.name());
|
||||
}
|
||||
}
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
package com.baeldung.stringtemplates;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class StringTemplatesUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenStringConcat_thenReturnComposedString() {
|
||||
StringCompositionTechniques stringCompositionTechniques = new StringCompositionTechniques();
|
||||
Assert.assertEquals("Today's weather is pleasant, with a temperature of 25 degrees Celsius", stringCompositionTechniques.composeUsingPlus("pleasant", "25", "Celsius"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenStringBuffer_thenReturnComposedString() {
|
||||
StringCompositionTechniques stringCompositionTechniques = new StringCompositionTechniques();
|
||||
Assert.assertEquals("Today's weather is pleasant, with a temperature of 25 degrees Celsius", stringCompositionTechniques.composeUsingStringBuffer("pleasant", "25", "Celsius"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenStringBuilder_thenReturnComposedString() {
|
||||
StringCompositionTechniques stringCompositionTechniques = new StringCompositionTechniques();
|
||||
Assert.assertEquals("Today's weather is pleasant, with a temperature of 25 degrees Celsius", stringCompositionTechniques.composeUsingStringBuilder("pleasant", "25", "Celsius"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenStringFormatter_thenReturnComposedFormattedString() {
|
||||
StringCompositionTechniques stringCompositionTechniques = new StringCompositionTechniques();
|
||||
Assert.assertEquals("Today's weather is pleasant, with a temperature of 25 degrees Celsius", stringCompositionTechniques.composeUsingFormatters("pleasant", "25", "Celsius"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenMessageFormatter_thenReturnComposedFormattedString() {
|
||||
StringCompositionTechniques stringCompositionTechniques = new StringCompositionTechniques();
|
||||
Assert.assertEquals("Today's weather is pleasant, with a temperature of 25 degrees Celsius", stringCompositionTechniques.composeUsingMessageFormatter("pleasant", "25", "Celsius"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingStringTemplateSTR_thenReturnInterpolatedString() {
|
||||
StringTemplateExamples templateExamples = new StringTemplateExamples();
|
||||
Assert.assertEquals("Today's weather is pleasant, with a temperature of 25 degrees Celsius", templateExamples.interpolationUsingSTRProcessor("pleasant", "25", "Celsius"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingMultilineStringTemplateSTR_thenReturnInterpolatedString() {
|
||||
StringTemplateExamples templateExamples = new StringTemplateExamples();
|
||||
Assert.assertEquals("{\n" + " \"feelsLike\": \"pleasant\",\n" + " \"temperature\": \"25\",\n" + " \"unit\": \"Celsius\"\n" + "}\n", templateExamples.interpolationOfJSONBlock("pleasant", "25", "Celsius"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingExpressionSTR_thenReturnInterpolatedString() {
|
||||
StringTemplateExamples templateExamples = new StringTemplateExamples();
|
||||
Assert.assertEquals("Today's weather is pleasant, with a temperature of 25 degrees Celsius", templateExamples.interpolationWithExpressions());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingExpressionRAW_thenReturnInterpolatedString() {
|
||||
StringTemplateExamples templateExamples = new StringTemplateExamples();
|
||||
Assert.assertEquals("Today's weather is pleasant, with a temperature of 25 degrees Celsius", templateExamples.interpolationWithTemplates());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingExpressionFMT_thenReturnInterpolatedString() {
|
||||
StringTemplateExamples templateExamples = new StringTemplateExamples();
|
||||
Assert.assertEquals("{\n" + " \"feelsLike\": \"pleasant\",\n" + " \"temperature\": \"25.86\",\n" + " \"unit\": \"Celsius\"\n" + "}\n", templateExamples.interpolationOfJSONBlockWithFMT("pleasant", 25.8636F, "Celsius"));
|
||||
}
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.unnamed.variables;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
class CarScenario {
|
||||
|
||||
protected final List<Car<?>> cars = List.of(
|
||||
new Car<>("Mitsubishi", "blue", new GasEngine()),
|
||||
new Car<>("Toyota", "red", new ElectricEngine()),
|
||||
new Car<>("Jaguar", "white", new HybridEngine())
|
||||
);
|
||||
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
package com.baeldung.unnamed.variables;
|
||||
|
||||
import static com.baeldung.unnamed.variables.UnnamedPatterns.getEngineTypeWithNamedPattern;
|
||||
import static com.baeldung.unnamed.variables.UnnamedPatterns.getEngineTypeWithUnnamedPattern;
|
||||
import static com.baeldung.unnamed.variables.UnnamedPatterns.getObjectsColorWithNamedPattern;
|
||||
import static com.baeldung.unnamed.variables.UnnamedPatterns.getObjectsColorWithSwitchAndNamedPattern;
|
||||
import static com.baeldung.unnamed.variables.UnnamedPatterns.getObjectsColorWithSwitchAndUnnamedPattern;
|
||||
import static com.baeldung.unnamed.variables.UnnamedPatterns.getObjectsColorWithUnnamedPattern;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class UnnamedPatternsUnitTest extends CarScenario {
|
||||
|
||||
@Test
|
||||
public void whenExtractingColorWithNamedPatterns_thenReturnBlue() {
|
||||
assertEquals("blue", getObjectsColorWithNamedPattern(cars.get(0)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenExtractingColorWithUnnamedPatterns_thenReturnBlue() {
|
||||
assertEquals("blue", getObjectsColorWithUnnamedPattern(cars.get(0)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenExtractingColorWithSwitchAndNamedPatterns_thenReturnBlue() {
|
||||
assertEquals("blue", getObjectsColorWithSwitchAndNamedPattern(cars.get(0)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenExtractingColorWithSwitchAndUnnamedPatterns_thenReturnBlue() {
|
||||
assertEquals("blue", getObjectsColorWithSwitchAndUnnamedPattern(cars.get(0)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenExtractingEngineTypeWithNamedPatterns_thenReturnGas() {
|
||||
assertEquals("gas", getEngineTypeWithNamedPattern(cars.get(0)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenExtractingEngineTypeWithUnnamedPatterns_thenReturnGas() {
|
||||
assertEquals("gas", getEngineTypeWithUnnamedPattern(cars.get(0)));
|
||||
}
|
||||
}
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
package com.baeldung.unnamed.variables;
|
||||
|
||||
import static com.baeldung.unnamed.variables.UnnamedVariables.countCarsOverLimitWithNamedVariable;
|
||||
import static com.baeldung.unnamed.variables.UnnamedVariables.countCarsOverLimitWithUnnamedVariable;
|
||||
import static com.baeldung.unnamed.variables.UnnamedVariables.getCarsByFirstLetterWithNamedVariables;
|
||||
import static com.baeldung.unnamed.variables.UnnamedVariables.getCarsByFirstLetterWithUnnamedVariables;
|
||||
import static com.baeldung.unnamed.variables.UnnamedVariables.handleCarExceptionWithNamedVariables;
|
||||
import static com.baeldung.unnamed.variables.UnnamedVariables.handleCarExceptionWithUnnamedVariables;
|
||||
import static com.baeldung.unnamed.variables.UnnamedVariables.obtainTransactionAndUpdateCarWithNamedVariables;
|
||||
import static com.baeldung.unnamed.variables.UnnamedVariables.obtainTransactionAndUpdateCarWithUnnamedVariables;
|
||||
import static com.baeldung.unnamed.variables.UnnamedVariables.removeThreeCarsAndReturnFirstRemovedWithNamedVariables;
|
||||
import static com.baeldung.unnamed.variables.UnnamedVariables.removeThreeCarsAndReturnFirstRemovedWithUnnamedVariables;
|
||||
import static com.baeldung.unnamed.variables.UnnamedVariables.sendNotificationToCarsWithNamedVariable;
|
||||
import static com.baeldung.unnamed.variables.UnnamedVariables.sendNotificationToCarsWithUnnamedVariable;
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.util.LinkedList;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class UnnamedVariablesUnitTest extends CarScenario {
|
||||
|
||||
@Test
|
||||
public void whenCountingCarsOverLimitWithNamedVariables_thenShouldReturnOne() {
|
||||
assertEquals(1, countCarsOverLimitWithNamedVariable(cars, 2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCountingCarsOverLimitWithUnnamedVariables_thenShouldReturnOne() {
|
||||
assertEquals(1, countCarsOverLimitWithUnnamedVariable(cars, 2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenNotifyingCarsWithNamedVariables_thenShouldNotFail() {
|
||||
assertDoesNotThrow(() -> sendNotificationToCarsWithNamedVariable(cars));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenNotifyingCarsWithUnnamedVariables_thenShouldNotFail() {
|
||||
assertDoesNotThrow(() -> sendNotificationToCarsWithUnnamedVariable(cars));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPollingCarsWithNamedVariables_thenReturnFirstOneAndEmptyQueue() {
|
||||
var carQueue = new LinkedList<>(cars);
|
||||
assertEquals("Mitsubishi", removeThreeCarsAndReturnFirstRemovedWithNamedVariables(carQueue).name());
|
||||
assertEquals(0, carQueue.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPollingCarsWithUnnamedVariables_thenReturnFirstOneAndEmptyQueue() {
|
||||
var carQueue = new LinkedList<>(cars);
|
||||
assertEquals("Mitsubishi", removeThreeCarsAndReturnFirstRemovedWithUnnamedVariables(carQueue).name());
|
||||
assertEquals(0, carQueue.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenHandlingExceptionWithNamedVariables_thenNoExceptionIsThrown() {
|
||||
assertDoesNotThrow(() -> handleCarExceptionWithNamedVariables(cars.get(0)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenHandlingExceptionWithUnnamedVariables_thenNoExceptionIsThrown() {
|
||||
assertDoesNotThrow(() -> handleCarExceptionWithUnnamedVariables(cars.get(0)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenHandlingTransactionUpdateWithNamedVariables_thenNoExceptionIsThrown() {
|
||||
assertDoesNotThrow(() -> obtainTransactionAndUpdateCarWithNamedVariables(cars.get(0)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenHandlingTransactionUpdateWithUnnamedVariables_thenNoExceptionIsThrown() {
|
||||
assertDoesNotThrow(() -> obtainTransactionAndUpdateCarWithUnnamedVariables(cars.get(0)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGettingCarsByFirstLetterWithNamedVariables_thenHaveThreeKeys() {
|
||||
var carsByLetter = getCarsByFirstLetterWithNamedVariables(cars);
|
||||
assertEquals(1, carsByLetter.get("M").size());
|
||||
assertEquals(1, carsByLetter.get("T").size());
|
||||
assertEquals(1, carsByLetter.get("J").size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGettingCarsByFirstLetterWithUnnamedVariables_thenHaveThreeKeys() {
|
||||
var carsByLetter = getCarsByFirstLetterWithUnnamedVariables(cars);
|
||||
assertEquals(1, carsByLetter.get("M").size());
|
||||
assertEquals(1, carsByLetter.get("T").size());
|
||||
assertEquals(1, carsByLetter.get("J").size());
|
||||
}
|
||||
}
|
||||
@@ -4,3 +4,4 @@ This module contains articles about Java 9 streams
|
||||
|
||||
### Relevant Articles:
|
||||
- [How to Break from Java Stream forEach](https://www.baeldung.com/java-break-stream-foreach)
|
||||
- [Creating Stream of Regex Matches](https://www.baeldung.com/java-stream-regex-matches)
|
||||
|
||||
@@ -9,3 +9,4 @@ This module contains complete guides about arrays in Java
|
||||
- [Guide to ArrayStoreException](https://www.baeldung.com/java-arraystoreexception)
|
||||
- [Creating a Generic Array in Java](https://www.baeldung.com/java-generic-array)
|
||||
- [Maximum Size of Java Arrays](https://www.baeldung.com/java-arrays-max-size)
|
||||
- [Merge Two Arrays and Remove Duplicates in Java](https://www.baeldung.com/java-merge-two-arrays-delete-duplicates)
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
## Relevant Articles
|
||||
- [Find the Middle Element of an Array in Java](https://www.baeldung.com/java-array-middle-item)
|
||||
@@ -14,4 +14,3 @@ This module contains articles about advanced operations on arrays in Java. They
|
||||
- [Slicing Arrays in Java](https://www.baeldung.com/java-slicing-arrays)
|
||||
- [Combining Two or More Byte Arrays](https://www.baeldung.com/java-concatenate-byte-arrays)
|
||||
- [Calculating the Sum of Two Arrays in Java](https://www.baeldung.com/java-sum-arrays-element-wise)
|
||||
- [Find the Middle Element of an Array in Java](https://www.baeldung.com/java-array-middle-item)
|
||||
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
package com.baeldung.incrementchar;
|
||||
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
class IncrementCharUnitTest {
|
||||
@Test
|
||||
void whenUsingForLoop_thenGenerateCharacters(){
|
||||
final List<Character> allCapitalCharacters = Arrays.asList('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z');
|
||||
List<Character> characters = new ArrayList<>();
|
||||
for (char character = 'A'; character <= 'Z'; character++) {
|
||||
characters.add(character);
|
||||
}
|
||||
Assertions.assertEquals(characters, allCapitalCharacters);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingStreams_thenGenerateCharacters() {
|
||||
final List<Character> allCapitalCharacters = Arrays.asList('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z');
|
||||
final List<Character> characters = IntStream.rangeClosed('A', 'Z').mapToObj(c -> (char) c).collect(Collectors.toList());
|
||||
Assertions.assertEquals(characters, allCapitalCharacters);
|
||||
}
|
||||
}
|
||||
+126
@@ -0,0 +1,126 @@
|
||||
package com.baeldung.skippingfirstelement;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.Set;
|
||||
|
||||
public class SkipFirstElementExample {
|
||||
|
||||
private final List<String> stringList = new ArrayList<>();
|
||||
private final Set<String> stringSet = new HashSet<>();
|
||||
private final Map<String, String> stringMap = new HashMap<>();
|
||||
|
||||
public SkipFirstElementExample() {
|
||||
// Initializing a List
|
||||
stringList.add("Monday");
|
||||
stringList.add("Tuesday");
|
||||
stringList.add("Wednesday");
|
||||
stringList.add("Thursday");
|
||||
stringList.add("Friday");
|
||||
stringList.add("Saturday");
|
||||
stringList.add("Sunday");
|
||||
// Initializing a Set
|
||||
stringSet.add("Monday");
|
||||
stringSet.add("Tuesday");
|
||||
stringSet.add("Wednesday");
|
||||
stringSet.add("Thursday");
|
||||
stringSet.add("Friday");
|
||||
stringSet.add("Saturday");
|
||||
stringSet.add("Sunday");
|
||||
// Initializing a Map
|
||||
stringMap.put("Monday", "The day when coffee is a life support system.");
|
||||
stringMap.put("Tuesday", "The day you realize that Monday's optimism was a lie.");
|
||||
stringMap.put("Wednesday", "Hump Day, or as it's known, the 'Is it Friday yet?' day.");
|
||||
stringMap.put("Thursday", "The day that says, 'Hold my beer, Friday is coming!'");
|
||||
stringMap.put("Friday", "The golden child of the weekdays. The superhero of the workweek.");
|
||||
stringMap.put("Saturday", "The day of rest? More like the day of 'What can I binge-watch next?'");
|
||||
stringMap.put("Sunday", "The day before you have to adult again.");
|
||||
}
|
||||
|
||||
void skippingFirstElementInListWithForLoop(List<String> stringList) {
|
||||
for (int i = 1; i < stringList.size(); i++) {
|
||||
process(stringList.get(i));
|
||||
}
|
||||
}
|
||||
|
||||
void skippingFirstElementInListWithWhileLoop(List<String> stringList) {
|
||||
final Iterator<String> iterator = stringList.iterator();
|
||||
if (iterator.hasNext()) {
|
||||
iterator.next();
|
||||
}
|
||||
while (iterator.hasNext()) {
|
||||
process(iterator.next());
|
||||
}
|
||||
}
|
||||
|
||||
void skippingFirstElementInSetWithWhileLoop(Set<String> stringSet) {
|
||||
final Iterator<String> iterator = stringSet.iterator();
|
||||
if (iterator.hasNext()) {
|
||||
iterator.next();
|
||||
}
|
||||
while (iterator.hasNext()) {
|
||||
process(iterator.next());
|
||||
}
|
||||
}
|
||||
|
||||
void skippingFirstElementInListWithWhileLoopStoringFirstElement(List<String> stringList) {
|
||||
final Iterator<String> iterator = stringList.iterator();
|
||||
String firstElement = null;
|
||||
if (iterator.hasNext()) {
|
||||
firstElement = iterator.next();
|
||||
}
|
||||
while (iterator.hasNext()) {
|
||||
process(iterator.next());
|
||||
// additional logic using fistElement
|
||||
}
|
||||
}
|
||||
|
||||
void skippingFirstElementInMapWithStreamSkip(Map<String, String> stringMap) {
|
||||
stringMap.entrySet().stream().skip(1).forEach(this::process);
|
||||
}
|
||||
|
||||
void skippingFirstElementInListWithSubList(List<String> stringList) {
|
||||
for (final String element : stringList.subList(1, stringList.size())) {
|
||||
process(element);
|
||||
}
|
||||
}
|
||||
|
||||
void skippingFirstElementInListWithForLoopWithAdditionalCheck(List<String> stringList) {
|
||||
for (int i = 0; i < stringList.size(); i++) {
|
||||
if (i == 0) {
|
||||
// do something else
|
||||
} else {
|
||||
process(stringList.get(i));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void skippingFirstElementInListWithWhileLoopWithCounter(List<String> stringList) {
|
||||
int counter = 0;
|
||||
while (counter < stringList.size()) {
|
||||
if (counter != 0) {
|
||||
process(stringList.get(counter));
|
||||
}
|
||||
++counter;
|
||||
}
|
||||
}
|
||||
|
||||
void skippingFirstElementInListWithReduce(List<String> stringList) {
|
||||
stringList.stream().reduce((skip, element) -> {
|
||||
process(element);
|
||||
return element;
|
||||
});
|
||||
}
|
||||
|
||||
protected void process(String string) {
|
||||
System.out.println(string);
|
||||
}
|
||||
protected void process(Entry<String, String> mapEntry) {
|
||||
System.out.println(mapEntry);
|
||||
}
|
||||
}
|
||||
+122
@@ -0,0 +1,122 @@
|
||||
package com.baeldung.skippingfirstelement;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Stream;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.condition.EnabledForJreRange;
|
||||
import org.junit.jupiter.api.condition.JRE;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
|
||||
@EnabledForJreRange(min = JRE.JAVA_9)
|
||||
class SkipFirstElementExampleUnitTest {
|
||||
|
||||
private static TestableSkipFirstElement testableSkip = new TestableSkipFirstElement();
|
||||
|
||||
@BeforeEach
|
||||
void setup() {
|
||||
testableSkip.reset();
|
||||
}
|
||||
|
||||
private static Stream<Arguments> listProvider() {
|
||||
return Stream.of(
|
||||
Arguments.of(
|
||||
List.of("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"),
|
||||
List.of("Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"))
|
||||
);
|
||||
}
|
||||
|
||||
private static Stream<Arguments> mapProvider() {
|
||||
return Stream.of(
|
||||
Arguments.of(
|
||||
Map.of(
|
||||
"Monday", "The day when coffee is a life support system.",
|
||||
"Tuesday", "The day you realize that Monday's optimism was a lie.",
|
||||
"Wednesday", "Hump Day, or as it's known, the 'Is it Friday yet?' day.",
|
||||
"Thursday", "The day that says, 'Hold my beer, Friday is coming!'",
|
||||
"Friday", "The golden child of the weekdays. The superhero of the workweek.",
|
||||
"Saturday", "The day of rest? More like the day of 'What can I binge-watch next?'",
|
||||
"Sunday", "The day before you have to adult again."
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("listProvider")
|
||||
void skippingFirstElementInListWithForLoop(List<String> input, List<String> expected) {
|
||||
testableSkip.skippingFirstElementInListWithForLoop(input);
|
||||
List<?> actual = testableSkip.getResult();
|
||||
assertEquals(actual, expected);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("listProvider")
|
||||
void skippingFirstElementInListWithWhileLoop(List<String> input, List<String> expected) {
|
||||
testableSkip.skippingFirstElementInListWithWhileLoop(input);
|
||||
List<?> actual = testableSkip.getResult();
|
||||
assertEquals(actual, expected);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("listProvider")
|
||||
void skippingFirstElementInSetWithWhileLoop(List<String> input) {
|
||||
testableSkip.skippingFirstElementInSetWithWhileLoop(new HashSet<>(input));
|
||||
Set<?> actual = new HashSet<>(testableSkip.getResult());
|
||||
assertEquals(actual.size(), input.size() - 1);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("listProvider")
|
||||
void skippingFirstElementInListWithWhileLoopStoringFirstElement(List<String> input, List<String> expected) {
|
||||
testableSkip.skippingFirstElementInListWithWhileLoopStoringFirstElement(input);
|
||||
List<?> actual = testableSkip.getResult();
|
||||
assertEquals(actual, expected);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("mapProvider")
|
||||
void skippingFirstElementInMapWithStreamSkip(Map<String, String> input) {
|
||||
testableSkip.skippingFirstElementInMapWithStreamSkip(input);
|
||||
List<?> actual = testableSkip.getResult();
|
||||
assertEquals(actual.size(), input.size() - 1);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("listProvider")
|
||||
void skippingFirstElementInListWithSubList(List<String> input, List<String> expected) {
|
||||
testableSkip.skippingFirstElementInListWithSubList(input);
|
||||
List<?> actual = testableSkip.getResult();
|
||||
assertEquals(actual, expected);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("listProvider")
|
||||
void skippingFirstElementInListWithForLoopWithAdditionalCheck(List<String> input, List<String> expected) {
|
||||
testableSkip.skippingFirstElementInListWithForLoopWithAdditionalCheck(input);
|
||||
List<?> actual = testableSkip.getResult();
|
||||
assertEquals(actual, expected);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("listProvider")
|
||||
void skippingFirstElementInListWithWhileLoopWithCounter(List<String> input, List<String> expected) {
|
||||
testableSkip.skippingFirstElementInListWithWhileLoopWithCounter(input);
|
||||
List<?> actual = testableSkip.getResult();
|
||||
assertEquals(actual, expected);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("listProvider")
|
||||
void skippingFirstElementInListWithReduce(List<String> input, List<String> expected) {
|
||||
testableSkip.skippingFirstElementInListWithReduce(input);
|
||||
List<?> actual = testableSkip.getResult();
|
||||
assertEquals(actual, expected);
|
||||
}
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
package com.baeldung.skippingfirstelement;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface TestableSkip {
|
||||
|
||||
void reset();
|
||||
|
||||
List<?> getResult();
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
package com.baeldung.skippingfirstelement;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map.Entry;
|
||||
|
||||
public class TestableSkipFirstElement extends SkipFirstElementExample implements TestableSkip {
|
||||
|
||||
|
||||
private List<String> processedList = new ArrayList<>();
|
||||
private List<Entry<String, String>> processedEntryList = new ArrayList<>();
|
||||
|
||||
@Override
|
||||
public void process(String string) {
|
||||
processedList.add(string);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void process(Entry<String, String> stringEntry) {
|
||||
processedEntryList.add(stringEntry);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void reset() {
|
||||
processedList.clear();
|
||||
processedEntryList.clear();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<?> getResult() {
|
||||
if (!processedList.isEmpty())
|
||||
return processedList;
|
||||
return processedEntryList;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
## Java Collections Cookbooks and Examples
|
||||
|
||||
This module contains articles about conversions among Collection types in Java.
|
||||
|
||||
### Relevant Articles:
|
||||
@@ -0,0 +1,26 @@
|
||||
<?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-collections-conversions-3</artifactId>
|
||||
<name>core-java-collections-conversions-3</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<build>
|
||||
<finalName>core-java-collections-conversions-3</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
</build>
|
||||
|
||||
</project>
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
package com.baeldung.hashmaptoarraylist;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import com.google.common.collect.Lists;
|
||||
import com.google.common.collect.Maps;
|
||||
import com.google.common.collect.Maps.EntryTransformer;
|
||||
|
||||
public class HashMapToArrayListConverterUtils {
|
||||
|
||||
static ArrayList<String> convertUsingConstructor(HashMap<Integer, String> hashMap) {
|
||||
if (hashMap == null) {
|
||||
return null;
|
||||
}
|
||||
return new ArrayList<String>(hashMap.values());
|
||||
}
|
||||
|
||||
static ArrayList<String> convertUsingAddAllMethod(HashMap<Integer, String> hashMap) {
|
||||
if (hashMap == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
ArrayList<String> arrayList = new ArrayList<String>(hashMap.size());
|
||||
arrayList.addAll(hashMap.values());
|
||||
|
||||
return arrayList;
|
||||
}
|
||||
|
||||
static ArrayList<String> convertUsingStreamApi(HashMap<Integer, String> hashMap) {
|
||||
if (hashMap == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return hashMap.values()
|
||||
.stream()
|
||||
.collect(Collectors.toCollection(ArrayList::new));
|
||||
}
|
||||
|
||||
static ArrayList<String> convertUsingForLoop(HashMap<Integer, String> hashMap) {
|
||||
if (hashMap == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
ArrayList<String> arrayList = new ArrayList<String>(hashMap.size());
|
||||
for (Map.Entry<Integer, String> entry : hashMap.entrySet()) {
|
||||
arrayList.add(entry.getValue());
|
||||
}
|
||||
|
||||
return arrayList;
|
||||
}
|
||||
|
||||
static public ArrayList<String> convertUsingGuava(HashMap<Integer, String> hashMap) {
|
||||
if (hashMap == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
EntryTransformer<Integer, String, String> entryMapTransformer = (key, value) -> value;
|
||||
|
||||
return Lists.newArrayList(Maps.transformEntries(hashMap, entryMapTransformer)
|
||||
.values());
|
||||
}
|
||||
|
||||
}
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
package com.baeldung.hashmaptoarraylist;
|
||||
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.containsInAnyOrder;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
public class HashMapToArrayListConverterUtilsUnitTest {
|
||||
|
||||
private HashMap<Integer, String> hashMap;
|
||||
|
||||
@Before
|
||||
public void beforeEach() {
|
||||
hashMap = new HashMap<>();
|
||||
hashMap.put(1, "AAA");
|
||||
hashMap.put(2, "BBB");
|
||||
hashMap.put(3, "CCC");
|
||||
hashMap.put(4, "DDD");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAHashMap_whenConvertUsingConstructor_thenReturnArrayList() {
|
||||
ArrayList<String> myList = HashMapToArrayListConverterUtils.convertUsingConstructor(hashMap);
|
||||
|
||||
assertThat(hashMap.values(), containsInAnyOrder(myList.toArray()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAHashMap_whenConvertUsingAddAllMethod_thenReturnArrayList() {
|
||||
ArrayList<String> myList = HashMapToArrayListConverterUtils.convertUsingAddAllMethod(hashMap);
|
||||
|
||||
assertThat(hashMap.values(), containsInAnyOrder(myList.toArray()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAHashMap_whenConvertUsingForLoop_thenReturnArrayList() {
|
||||
ArrayList<String> myList = HashMapToArrayListConverterUtils.convertUsingForLoop(hashMap);
|
||||
|
||||
assertThat(hashMap.values(), containsInAnyOrder(myList.toArray()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAHashMap_whenConvertUsingStreamApi_thenReturnArrayList() {
|
||||
ArrayList<String> myList = HashMapToArrayListConverterUtils.convertUsingStreamApi(hashMap);
|
||||
|
||||
assertThat(hashMap.values(), containsInAnyOrder(myList.toArray()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAHashMap_whenConvertUsingGuava_thenReturnArrayList() {
|
||||
ArrayList<String> myList = HashMapToArrayListConverterUtils.convertUsingGuava(hashMap);
|
||||
|
||||
assertThat(hashMap.values(), containsInAnyOrder(myList.toArray()));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
## Relevant Articles
|
||||
- [Check if a List Contains a String Element While Ignoring Case](https://www.baeldung.com/java-list-search-case-insensitive)
|
||||
@@ -0,0 +1,15 @@
|
||||
<?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-collections-list-6</artifactId>
|
||||
<name>core-java-collections-list-6</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
</project>
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
package com.baeldung.lists;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class StringListCaseInsensitiveContainsUnitTest {
|
||||
private final static List<String> THE_LIST = List.of("Game of Thrones", "Forrest Gump", "American Beauty", "Pretty Woman", "Catch Me If You Can");
|
||||
|
||||
@Test
|
||||
void whenUsingContains_thenGetExpectedResult() {
|
||||
assertFalse(THE_LIST.contains("catch me if you can"));
|
||||
}
|
||||
|
||||
boolean ignoreCaseContainsForLoop(List<String> list, String value) {
|
||||
for (String e : list) {
|
||||
if (value.equalsIgnoreCase(e))
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingIgnoreCaseContainsForLoop_thenGetExpectedResult() {
|
||||
assertTrue(ignoreCaseContainsForLoop(THE_LIST, "CATCH me if you CAN"));
|
||||
assertTrue(ignoreCaseContainsForLoop(THE_LIST, "game of thrones"));
|
||||
assertFalse(ignoreCaseContainsForLoop(THE_LIST, "The Godfather"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingIgnoreCaseContainsStream_thenGetExpectedResult() {
|
||||
assertTrue(THE_LIST.stream()
|
||||
.anyMatch(e -> e.equalsIgnoreCase("CATCH me if you CAN")));
|
||||
|
||||
assertTrue(THE_LIST.stream()
|
||||
.anyMatch("game of thrones"::equalsIgnoreCase));
|
||||
|
||||
assertFalse(THE_LIST.stream()
|
||||
.anyMatch("The Godfather"::equalsIgnoreCase));
|
||||
}
|
||||
}
|
||||
-76
@@ -1,76 +0,0 @@
|
||||
package java.com.baeldung.objecttomap;
|
||||
import com.google.gson.Gson;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import wiremock.com.fasterxml.jackson.core.type.TypeReference;
|
||||
import wiremock.com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import wiremock.com.google.common.reflect.TypeToken;
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public class ObjectToMapUnitTest {
|
||||
Employee employee = new Employee("John", 3000.0);
|
||||
|
||||
@Test
|
||||
public void givenJavaObject_whenUsingReflection_thenConvertToMap() throws IllegalAccessException {
|
||||
Map<String, Object> map = convertUsingReflection(employee);
|
||||
Assert.assertEquals(employee.getName(), map.get("name"));
|
||||
Assert.assertEquals(employee.getSalary(), map.get("salary"));
|
||||
}
|
||||
|
||||
private Map<String, Object> convertUsingReflection(Object object) throws IllegalAccessException {
|
||||
Map<String, Object> map = new HashMap<>();
|
||||
Field[] fields = object.getClass().getDeclaredFields();
|
||||
|
||||
for (Field field : fields) {
|
||||
field.setAccessible(true);
|
||||
map.put(field.getName(), field.get(object));
|
||||
}
|
||||
|
||||
return map;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenJavaObject_whenUsingJackson_thenConvertToMap() {
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
Map<String, Object> map = objectMapper.convertValue(employee, new TypeReference<Map<String, Object>>() {});
|
||||
Assert.assertEquals(employee.getName(), map.get("name"));
|
||||
Assert.assertEquals(employee.getSalary(), map.get("salary"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenJavaObject_whenUsingGson_thenConvertToMap() {
|
||||
Gson gson = new Gson();
|
||||
String json = gson.toJson(employee);
|
||||
Map<String, Object> map = gson.fromJson(json, new TypeToken<Map<String, Object>>() {}.getType());
|
||||
Assert.assertEquals(employee.getName(), map.get("name"));
|
||||
Assert.assertEquals(employee.getSalary(), map.get("salary"));
|
||||
}
|
||||
|
||||
private static class Employee {
|
||||
private String name;
|
||||
private Double salary;
|
||||
|
||||
public Employee(String name, Double salary) {
|
||||
this.name = name;
|
||||
this.salary = salary;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Double getSalary() {
|
||||
return salary;
|
||||
}
|
||||
|
||||
public void setSalary(Double age) {
|
||||
this.salary = salary;
|
||||
}
|
||||
}
|
||||
}
|
||||
+128
@@ -0,0 +1,128 @@
|
||||
package com.baeldung.objecttomap;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.google.common.reflect.TypeToken;
|
||||
import com.google.gson.Gson;
|
||||
import org.junit.Test;
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.SortedMap;
|
||||
import java.util.TreeMap;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class ObjectToMapUnitTest {
|
||||
Employee employee = new Employee("John", 3000.0);
|
||||
|
||||
@Test
|
||||
public void givenJavaObject_whenUsingReflection_thenConvertToMap() throws IllegalAccessException {
|
||||
Map<String, Object> map = convertUsingReflection(employee);
|
||||
assertEquals(employee.getName(), map.get("name"));
|
||||
assertEquals(employee.getSalary(), map.get("salary"));
|
||||
}
|
||||
|
||||
private Map<String, Object> convertUsingReflection(Object object) throws IllegalAccessException {
|
||||
Map<String, Object> map = new HashMap<>();
|
||||
Field[] fields = object.getClass().getDeclaredFields();
|
||||
|
||||
for (Field field : fields) {
|
||||
field.setAccessible(true);
|
||||
map.put(field.getName(), field.get(object));
|
||||
}
|
||||
|
||||
return map;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenJavaObject_whenUsingJackson_thenConvertToMap() {
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
Map<String, Object> map = objectMapper.convertValue(employee, new TypeReference<Map<String, Object>>() {});
|
||||
assertEquals(employee.getName(), map.get("name"));
|
||||
assertEquals(employee.getSalary(), map.get("salary"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenJavaObject_whenUsingGson_thenConvertToMap() {
|
||||
Gson gson = new Gson();
|
||||
String json = gson.toJson(employee);
|
||||
Map<String, Object> map = gson.fromJson(json, new TypeToken<Map<String, Object>>() {}.getType());
|
||||
assertEquals(employee.getName(), map.get("name"));
|
||||
assertEquals(employee.getSalary(), map.get("salary"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void given_UnsortedMap_whenSortingByValueDescending_thenValuesAreInDescendingOrder() {
|
||||
Map<String, Integer> unsortedMap = new HashMap<>();
|
||||
unsortedMap.put("one", 1);
|
||||
unsortedMap.put("three", 3);
|
||||
unsortedMap.put("five", 5);
|
||||
unsortedMap.put("two", 2);
|
||||
unsortedMap.put("four", 4);
|
||||
|
||||
Map<String, Integer> sortedMap = sortMapByValueDescending(unsortedMap);
|
||||
|
||||
assertEquals(5, sortedMap.size());
|
||||
final Iterator<Integer> iterator = sortedMap.values().iterator();
|
||||
assertEquals(5, (int) iterator.next());
|
||||
assertEquals(4, (int) iterator.next());
|
||||
assertEquals(3, (int) iterator.next());
|
||||
assertEquals(2, (int) iterator.next());
|
||||
assertEquals(1, (int) iterator.next());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void given_UnsortedMap_whenUsingTreeMap_thenKeysAreInDescendingOrder() {
|
||||
SortedMap<String, Integer> treeMap = new TreeMap<>(Comparator.reverseOrder());
|
||||
treeMap.put("one", 1);
|
||||
treeMap.put("three", 3);
|
||||
treeMap.put("five", 5);
|
||||
treeMap.put("two", 2);
|
||||
treeMap.put("four", 4);
|
||||
|
||||
assertEquals(5, treeMap.size());
|
||||
final Iterator<String> iterator = treeMap.keySet().iterator();
|
||||
assertEquals("two", iterator.next());
|
||||
assertEquals("three", iterator.next());
|
||||
assertEquals("one", iterator.next());
|
||||
assertEquals("four", iterator.next());
|
||||
assertEquals("five", iterator.next());
|
||||
}
|
||||
|
||||
private static class Employee {
|
||||
private String name;
|
||||
private Double salary;
|
||||
|
||||
public Employee(String name, Double salary) {
|
||||
this.name = name;
|
||||
this.salary = salary;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Double getSalary() {
|
||||
return salary;
|
||||
}
|
||||
|
||||
public void setSalary(Double age) {
|
||||
this.salary = salary;
|
||||
}
|
||||
}
|
||||
|
||||
public static <K, V extends Comparable<? super V>> Map<K, V> sortMapByValueDescending(Map<K, V> map) {
|
||||
return map.entrySet().stream()
|
||||
.sorted(Map.Entry.<K, V>comparingByValue().reversed())
|
||||
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
|
||||
}
|
||||
}
|
||||
+44
-9
@@ -96,7 +96,8 @@ public class DateTimeFormatterUnitTest {
|
||||
String newYorkDateTimePattern = "dd.MM.yyyy HH:mm z";
|
||||
DateTimeFormatter newYorkDateFormatter = DateTimeFormatter.ofPattern(newYorkDateTimePattern);
|
||||
LocalDateTime summerDay = LocalDateTime.of(2016, 7, 31, 14, 15);
|
||||
Assert.assertEquals("31.07.2016 14:15 EDT", newYorkDateFormatter.format(ZonedDateTime.of(summerDay, ZoneId.of("America/New_York"))));
|
||||
Assert.assertEquals("31.07.2016 14:15 EDT",
|
||||
newYorkDateFormatter.format(ZonedDateTime.of(summerDay, ZoneId.of("America/New_York"))));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -121,8 +122,10 @@ public class DateTimeFormatterUnitTest {
|
||||
@Test
|
||||
public void shouldPrintFormattedDateTimeWithPredefined() {
|
||||
Assert.assertEquals("2018-03-09", DateTimeFormatter.ISO_LOCAL_DATE.format(LocalDate.of(2018, 3, 9)));
|
||||
Assert.assertEquals("2018-03-09-03:00", DateTimeFormatter.ISO_OFFSET_DATE.format(LocalDate.of(2018, 3, 9).atStartOfDay(ZoneId.of("UTC-3"))));
|
||||
Assert.assertEquals("Fri, 9 Mar 2018 00:00:00 -0300", DateTimeFormatter.RFC_1123_DATE_TIME.format(LocalDate.of(2018, 3, 9).atStartOfDay(ZoneId.of("UTC-3"))));
|
||||
Assert.assertEquals("2018-03-09-03:00",
|
||||
DateTimeFormatter.ISO_OFFSET_DATE.format(LocalDate.of(2018, 3, 9).atStartOfDay(ZoneId.of("UTC-3"))));
|
||||
Assert.assertEquals("Fri, 9 Mar 2018 00:00:00 -0300",
|
||||
DateTimeFormatter.RFC_1123_DATE_TIME.format(LocalDate.of(2018, 3, 9).atStartOfDay(ZoneId.of("UTC-3"))));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -165,30 +168,62 @@ public class DateTimeFormatterUnitTest {
|
||||
public void shouldPrintFormattedZonedDateTime() {
|
||||
ZonedDateTime zonedDateTime = ZonedDateTime.of(2021, 02, 15, 0, 0, 0, 0, ZoneId.of("Europe/Paris"));
|
||||
String formattedZonedDateTime = DateTimeFormatter.ISO_INSTANT.format(zonedDateTime);
|
||||
|
||||
|
||||
Assert.assertEquals("2021-02-14T23:00:00Z", formattedZonedDateTime);
|
||||
}
|
||||
|
||||
|
||||
@Test(expected = UnsupportedTemporalTypeException.class)
|
||||
public void shouldExpectAnExceptionIfInputIsLocalDateTime() {
|
||||
DateTimeFormatter.ISO_INSTANT.format(LocalDate.now());
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void shouldParseZonedDateTime() {
|
||||
DateTimeFormatter formatter = DateTimeFormatter.ISO_INSTANT.withZone(ZoneId.systemDefault());
|
||||
ZonedDateTime zonedDateTime = ZonedDateTime.parse("2021-10-01T05:06:20Z", formatter);
|
||||
|
||||
|
||||
Assert.assertEquals("2021-10-01T05:06:20Z", DateTimeFormatter.ISO_INSTANT.format(zonedDateTime));
|
||||
}
|
||||
|
||||
|
||||
@Test(expected = DateTimeParseException.class)
|
||||
public void shouldExpectAnExceptionIfTimeZoneIsMissing() {
|
||||
ZonedDateTime zonedDateTime = ZonedDateTime.parse("2021-11-01T05:06:20Z", DateTimeFormatter.ISO_INSTANT);
|
||||
}
|
||||
|
||||
|
||||
@Test(expected = DateTimeParseException.class)
|
||||
public void shouldExpectAnExceptionIfSecondIsMissing() {
|
||||
ZonedDateTime zonedDateTime = ZonedDateTime.parse("2021-12-02T08:06Z", DateTimeFormatter.ISO_INSTANT);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUSShortFormatting() {
|
||||
LocalDate date = LocalDate.of(2023, 9, 18);
|
||||
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM dd, yy: EEE").withLocale(Locale.US);
|
||||
String formattedDate = date.format(formatter);
|
||||
Assert.assertEquals("Sep 18, 23: Mon", formattedDate);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUSFullFormatting() {
|
||||
LocalDate date = LocalDate.of(2023, 9, 18);
|
||||
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMM dd, yyyy: EEEE").withLocale(Locale.US);
|
||||
String formattedDate = date.format(formatter);
|
||||
Assert.assertEquals("September 18, 2023: Monday", formattedDate);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testKoreanShortFormatting() {
|
||||
LocalDate date = LocalDate.of(2023, 9, 18);
|
||||
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM dd, yy: EEE").withLocale(Locale.KOREA);
|
||||
String formattedDate = date.format(formatter);
|
||||
Assert.assertEquals("9월 18, 23: 월", formattedDate);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testKoreanFullFormatting() {
|
||||
LocalDate date = LocalDate.of(2023, 9, 18);
|
||||
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMM dd, yyyy: EEEE").withLocale(Locale.KOREA);
|
||||
String formattedDate = date.format(formatter);
|
||||
Assert.assertEquals("9월 18, 2023: 월요일", formattedDate);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,4 +3,4 @@
|
||||
### Relevant Articles:
|
||||
|
||||
- [Introduction to Javadoc](http://www.baeldung.com/javadoc)
|
||||
|
||||
- [Code Snippets in Java API Documentation](https://www.baeldung.com/java-doc-code-snippets)
|
||||
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package com.baeldung.snippettag;
|
||||
|
||||
/**
|
||||
*
|
||||
* External code snippet showing the loop process in binary search method.
|
||||
* {@snippet class="BinarySearch" region="binary"}
|
||||
*
|
||||
* Time Zone
|
||||
* {@snippet file="application.properties" region="zone"}
|
||||
*
|
||||
*/
|
||||
|
||||
public class GreetingsExternalSnippet {
|
||||
public void helloBinarySearch() {
|
||||
System.out.println("Hi, it's great knowing that binary search uses a loop under the hood");
|
||||
}
|
||||
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
package com.baeldung.snippettag;
|
||||
|
||||
|
||||
/**
|
||||
* The code below shows a full highlighted line
|
||||
* {@snippet :
|
||||
* public void helloBaeldung() {
|
||||
* System.out.println("Hello From Team Baeldung"); // @highlight
|
||||
* }
|
||||
* }
|
||||
*
|
||||
* highlighting a substring
|
||||
* {@snippet :
|
||||
* public void helloBaeldung() {
|
||||
* System.out.println("Hello From Team Baeldung"); // @highlight substring="println"
|
||||
* }
|
||||
* }
|
||||
*
|
||||
* highlighting texts on multiple lines
|
||||
* {@snippet :
|
||||
* public void helloBaeldung() {
|
||||
* System.out.println("Hello From Team Baeldung"); // @highlight region substring="println"
|
||||
* String country = "USA";
|
||||
* System.out.println("Hello From Team " + country); // @end
|
||||
* }
|
||||
* }
|
||||
*
|
||||
*/
|
||||
|
||||
public class GreetingsHighlightTag {
|
||||
public void helloBaeldung() {
|
||||
System.out.println("Hello From Team Baeldung");
|
||||
}
|
||||
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package com.baeldung.snippettag;
|
||||
|
||||
/**
|
||||
* The code below shows the content of {@code helloBaeldung()} method
|
||||
* {@snippet :
|
||||
* public void helloBaeldung() {
|
||||
* System.out.println("Hello From Team Baeldung");
|
||||
* }
|
||||
* }
|
||||
*/
|
||||
|
||||
public class GreetingsInlineSnippet {
|
||||
public void helloBaeldung() {
|
||||
System.out.println("Hello From Team Baeldung");
|
||||
}
|
||||
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package com.baeldung.snippettag;
|
||||
|
||||
/**
|
||||
*
|
||||
* Using the replace tag
|
||||
* {@snippet :
|
||||
* public void helloBaeldung() {
|
||||
* System.out.println("Hello From Team Baeldung"); // @replace regex='".*"' replacement="..."
|
||||
* }
|
||||
* }
|
||||
* Using the link tag
|
||||
* {@snippet :
|
||||
* public void helloBaeldung() {
|
||||
* System.out.println("Hello From Team Baeldung"); // @link substring="System.out" target="System#out"
|
||||
* }
|
||||
* }
|
||||
*
|
||||
*/
|
||||
|
||||
public class GreetingsReplaceAndLinkTag {
|
||||
public void helloBaeldung() {
|
||||
System.out.println("Hello From Team Baeldung");
|
||||
}
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
|
||||
public class BinarySearch {
|
||||
|
||||
public int search(int[] list, int item) {
|
||||
int index = Integer.MAX_VALUE;
|
||||
int low = 0;
|
||||
int high = list.length - 1;
|
||||
// @start region="binary"
|
||||
while (low <= high) {
|
||||
int mid = high - low;
|
||||
int guess = list[mid];
|
||||
if (guess == item) {
|
||||
index = mid;
|
||||
break;
|
||||
} else if (guess > item) {
|
||||
low = mid - 1;
|
||||
} else {
|
||||
low = mid + 1;
|
||||
}
|
||||
low++;
|
||||
}
|
||||
// @end region="binary"
|
||||
|
||||
return index;
|
||||
}
|
||||
|
||||
}
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
# @start region="zone"
|
||||
local.timezone = GMT+1
|
||||
local.zip = 94123
|
||||
# @end region="zone"
|
||||
@@ -0,0 +1,2 @@
|
||||
test-link*
|
||||
0.*
|
||||
@@ -0,0 +1,8 @@
|
||||
## Core Java IO
|
||||
|
||||
This module contains articles about core Java input and output (IO)
|
||||
|
||||
### Relevant Articles:
|
||||
|
||||
- [[<-- Prev]](/core-java-modules/core-java-io-4)
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
<?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-io-5</artifactId>
|
||||
<name>core-java-io-5</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<!-- Mime Type Resolution Libraries -->
|
||||
<dependency>
|
||||
<groupId>org.apache.tika</groupId>
|
||||
<artifactId>tika-core</artifactId>
|
||||
<version>${tika.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>net.sf.jmimemagic</groupId>
|
||||
<artifactId>jmimemagic</artifactId>
|
||||
<version>${jmime-magic.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.jodd</groupId>
|
||||
<artifactId>jodd-util</artifactId>
|
||||
<version>${jodd-util.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.j256.simplemagic</groupId>
|
||||
<artifactId>simplemagic</artifactId>
|
||||
<version>${simplemagic.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>core-java-io-5</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<configuration>
|
||||
<source>11</source>
|
||||
<target>11</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<!-- Mime Type Libraries -->
|
||||
<tika.version>2.8.0</tika.version>
|
||||
<jmime-magic.version>0.1.5</jmime-magic.version>
|
||||
<jodd-util.version>6.2.1</jodd-util.version>
|
||||
<simplemagic.version>1.17</simplemagic.version>
|
||||
</properties>
|
||||
</project>
|
||||
+3
-5
@@ -11,10 +11,8 @@ import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import org.apache.tika.mime.MimeTypeException;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.j256.simplemagic.ContentType;
|
||||
import org.junit.Test;
|
||||
|
||||
public class ExtensionFromMimeTypeUnitTest {
|
||||
private static final String IMAGE_JPEG_MIME_TYPE = "image/jpeg";
|
||||
@@ -37,14 +35,14 @@ public class ExtensionFromMimeTypeUnitTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingMimetypesFileTypeMap_thenGetFileExtension() {
|
||||
public void whenUsingSimpleMagic_thenGetFileExtension() {
|
||||
List<String> expectedExtensions = Arrays.asList("jpeg", "jpg", "jpe");
|
||||
String[] detectedExtensions = ContentType.fromMimeType(IMAGE_JPEG_MIME_TYPE).getFileExtensions();
|
||||
assertThat(detectedExtensions).containsExactlyElementsOf(expectedExtensions);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingCustomLogic_thenGetFileExtension() {
|
||||
public void whenUsingCustomMap_thenGetFileExtension() {
|
||||
Map<String, Set<String>> mimeExtensionsMap = new HashMap<>();
|
||||
List<String> expectedExtensions = Arrays.asList(".jpg", ".jpe", ".jpeg");
|
||||
addMimeExtensions(mimeExtensionsMap, "image/jpeg", ".jpg");
|
||||
@@ -7,3 +7,4 @@ This module contains articles about core Java input/output(IO) APIs.
|
||||
- [Get the Desktop Path in Java](https://www.baeldung.com/java-desktop-path)
|
||||
- [Check if a File Is Empty in Java](https://www.baeldung.com/java-check-file-empty)
|
||||
- [Converting Relative to Absolute Paths in Java](https://www.baeldung.com/java-from-relative-to-absolute-paths)
|
||||
- [Detect EOF in Java](https://www.baeldung.com/java-file-detect-end-of-file)
|
||||
|
||||
@@ -43,17 +43,6 @@
|
||||
<version>${angus-activation.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.jodd</groupId>
|
||||
<artifactId>jodd-util</artifactId>
|
||||
<version>${jodd-util.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.j256.simplemagic</groupId>
|
||||
<artifactId>simplemagic</artifactId>
|
||||
<version>${simplemagic.version}</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
@@ -153,8 +142,6 @@
|
||||
<fscontext.version>4.4.2</fscontext.version>
|
||||
<jakarta-activation-api.version>2.1.2</jakarta-activation-api.version>
|
||||
<angus-activation.version>2.0.1</angus-activation.version>
|
||||
<jodd-util.version>6.2.1</jodd-util.version>
|
||||
<simplemagic.version>1.17</simplemagic.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
@@ -18,7 +18,11 @@
|
||||
<artifactId>mapstruct</artifactId>
|
||||
<version>${mapstruct.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<build>
|
||||
<plugins>
|
||||
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
package com.baeldung.compareobjects;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
public class Address {
|
||||
private String streetAddress;
|
||||
private String city;
|
||||
private String postalCode;
|
||||
|
||||
public Address(String streetAddress, String city, String postalCode) {
|
||||
this.streetAddress = streetAddress;
|
||||
this.city = city;
|
||||
this.postalCode = postalCode;
|
||||
}
|
||||
|
||||
public String getStreetAddress() {
|
||||
return streetAddress;
|
||||
}
|
||||
|
||||
public String getCity() {
|
||||
return city;
|
||||
}
|
||||
|
||||
public String getPostalCode() {
|
||||
return postalCode;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Address{" + "streetAddress='" + streetAddress + '\'' + ", city='" + city + '\'' + ", postalCode='" + postalCode + '\'' + '}';
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o)
|
||||
return true;
|
||||
if (o == null || getClass() != o.getClass())
|
||||
return false;
|
||||
Address address = (Address) o;
|
||||
return Objects.equals(streetAddress, address.streetAddress) && Objects.equals(city, address.city) && Objects.equals(postalCode, address.postalCode);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(streetAddress, city, postalCode);
|
||||
}
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
package com.baeldung.compareobjects;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
import org.apache.commons.lang3.builder.DiffExclude;
|
||||
|
||||
public class Person {
|
||||
private String firstName;
|
||||
private String lastName;
|
||||
private int age;
|
||||
private List<PhoneNumber> phoneNumbers;
|
||||
@DiffExclude
|
||||
private Address address;
|
||||
|
||||
public Person(String firstName, String lastName, int age, List<PhoneNumber> phoneNumbers, Address address) {
|
||||
this.firstName = firstName;
|
||||
this.lastName = lastName;
|
||||
this.age = age;
|
||||
this.phoneNumbers = phoneNumbers;
|
||||
this.address = address;
|
||||
}
|
||||
|
||||
public String getFirstName() {
|
||||
return firstName;
|
||||
}
|
||||
|
||||
public String getLastName() {
|
||||
return lastName;
|
||||
}
|
||||
|
||||
public int getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
public List<PhoneNumber> getPhoneNumbers() {
|
||||
return phoneNumbers;
|
||||
}
|
||||
|
||||
public Address getAddress() {
|
||||
return address;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o)
|
||||
return true;
|
||||
if (o == null || getClass() != o.getClass())
|
||||
return false;
|
||||
Person person = (Person) o;
|
||||
return age == person.age && Objects.equals(firstName, person.firstName) && Objects.equals(lastName, person.lastName) && Objects.equals(phoneNumbers, person.phoneNumbers) && Objects.equals(address, person.address);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(firstName, lastName, age, phoneNumbers, address);
|
||||
}
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
package com.baeldung.compareobjects;
|
||||
|
||||
import org.apache.commons.lang3.builder.DiffBuilder;
|
||||
import org.apache.commons.lang3.builder.DiffResult;
|
||||
import org.apache.commons.lang3.builder.ToStringStyle;
|
||||
|
||||
public class PersonDiffBuilder {
|
||||
public static DiffResult compare(Person first, Person second) {
|
||||
DiffBuilder diffBuilder = new DiffBuilder(first, second, ToStringStyle.DEFAULT_STYLE).append("person", first.getFirstName(), second.getFirstName())
|
||||
.append("lastName", first.getLastName(), second.getLastName())
|
||||
.append("streetAddress", first.getAddress()
|
||||
.getStreetAddress(), second.getAddress()
|
||||
.getStreetAddress())
|
||||
.append("city", first.getAddress()
|
||||
.getCity(), second.getAddress()
|
||||
.getCity())
|
||||
.append("postalCode", first.getAddress()
|
||||
.getPostalCode(), second.getAddress()
|
||||
.getPostalCode())
|
||||
.append("age", first.getAge(), second.getAge());
|
||||
|
||||
for (int i = 0; i < first.getPhoneNumbers()
|
||||
.size(); i++) {
|
||||
diffBuilder.append("phoneNumbers[" + i + "].number", first.getPhoneNumbers()
|
||||
.get(i)
|
||||
.getNumber(), second.getPhoneNumbers()
|
||||
.get(i)
|
||||
.getNumber());
|
||||
}
|
||||
return diffBuilder.build();
|
||||
}
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
package com.baeldung.compareobjects;
|
||||
|
||||
import org.apache.commons.lang3.builder.DiffResult;
|
||||
import org.apache.commons.lang3.builder.ReflectionDiffBuilder;
|
||||
import org.apache.commons.lang3.builder.ToStringStyle;
|
||||
|
||||
public class PersonReflectionDiffBuilder {
|
||||
public static DiffResult compare(Person first, Person second) {
|
||||
return new ReflectionDiffBuilder<>(first, second, ToStringStyle.SHORT_PREFIX_STYLE).build();
|
||||
}
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
package com.baeldung.compareobjects;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
import org.apache.commons.lang3.builder.DiffExclude;
|
||||
|
||||
public class PhoneNumber {
|
||||
private String type;
|
||||
private String number;
|
||||
|
||||
public PhoneNumber(String type, String number) {
|
||||
this.type = type;
|
||||
this.number = number;
|
||||
}
|
||||
|
||||
public String getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
public String getNumber() {
|
||||
return number;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "PhoneNumber{" + "type='" + type + '\'' + ", number='" + number + '\'' + '}';
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o)
|
||||
return true;
|
||||
if (o == null || getClass() != o.getClass())
|
||||
return false;
|
||||
PhoneNumber that = (PhoneNumber) o;
|
||||
return Objects.equals(number, that.number);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(number);
|
||||
}
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
package com.baeldung.compareobjects;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.apache.commons.lang3.builder.Diff;
|
||||
import org.apache.commons.lang3.builder.DiffResult;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class PersonDiffBuilderUnitTest {
|
||||
|
||||
@Test
|
||||
void givenTwoPeopleDifferent_whenComparingWithDiffBuilder_thenDifferencesFound() {
|
||||
List<PhoneNumber> phoneNumbers1 = new ArrayList<>();
|
||||
phoneNumbers1.add(new PhoneNumber("home", "123-456-7890"));
|
||||
phoneNumbers1.add(new PhoneNumber("work", "987-654-3210"));
|
||||
|
||||
List<PhoneNumber> phoneNumbers2 = new ArrayList<>();
|
||||
phoneNumbers2.add(new PhoneNumber("mobile1", "123-456-7890"));
|
||||
phoneNumbers2.add(new PhoneNumber("mobile2", "987-654-3210"));
|
||||
|
||||
Address address1 = new Address("123 Main St", "London", "12345");
|
||||
Address address2 = new Address("123 Main St", "Paris", "54321");
|
||||
|
||||
Person person1 = new Person("John", "Doe", 30, phoneNumbers1, address1);
|
||||
Person person2 = new Person("Jane", "Smith", 28, phoneNumbers2, address2);
|
||||
|
||||
DiffResult<Person> diff = PersonDiffBuilder.compare(person1, person2);
|
||||
for (Diff<?> d : diff.getDiffs()) {
|
||||
System.out.println(d.getFieldName() + ": " + d.getLeft() + " != " + d.getRight());
|
||||
}
|
||||
|
||||
assertFalse(diff.getDiffs()
|
||||
.isEmpty());
|
||||
}
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
package com.baeldung.compareobjects;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.apache.commons.lang3.builder.Diff;
|
||||
import org.apache.commons.lang3.builder.DiffResult;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class PersonReflectionDiffBuilderUnitTest {
|
||||
@Test
|
||||
void givenTwoPeopleDifferent_whenComparingWithReflectionDiffBuilder_thenDifferencesFound() {
|
||||
List<PhoneNumber> phoneNumbers1 = new ArrayList<>();
|
||||
phoneNumbers1.add(new PhoneNumber("home", "123-456-7890"));
|
||||
phoneNumbers1.add(new PhoneNumber("work", "987-654-3210"));
|
||||
|
||||
List<PhoneNumber> phoneNumbers2 = new ArrayList<>();
|
||||
phoneNumbers2.add(new PhoneNumber("mobile1", "123-456-7890"));
|
||||
phoneNumbers2.add(new PhoneNumber("mobile2", "987-654-3210"));
|
||||
|
||||
Address address1 = new Address("123 Main St", "London", "12345");
|
||||
Address address2 = new Address("123 Main St", "Paris", "54321");
|
||||
|
||||
Person person1 = new Person("John", "Doe", 30, phoneNumbers1, address1);
|
||||
Person person2 = new Person("Jane", "Smith", 28, phoneNumbers2, address2);
|
||||
|
||||
DiffResult<Person> diff = PersonReflectionDiffBuilder.compare(person1, person2);
|
||||
for (Diff<?> d : diff.getDiffs()) {
|
||||
System.out.println(d.getFieldName() + ": " + d.getLeft() + " != " + d.getRight());
|
||||
}
|
||||
|
||||
assertFalse(diff.getDiffs()
|
||||
.isEmpty());
|
||||
}
|
||||
}
|
||||
@@ -4,4 +4,5 @@
|
||||
- [Integer.class vs Integer.TYPE vs int.class](https://www.baeldung.com/java-integer-class-vs-type-vs-int)
|
||||
- [Does Java Read Integers in Little Endian or Big Endian?](https://www.baeldung.com/java-integers-little-big-endian)
|
||||
- [How to Split an Integer Number Into Digits in Java](https://www.baeldung.com/java-integer-individual-digits)
|
||||
- [Java Double vs. BigDecimal](https://www.baeldung.com/java-double-vs-bigdecimal)
|
||||
- More articles: [[<-- prev]](../core-java-numbers-5)
|
||||
|
||||
@@ -18,6 +18,18 @@
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.testng</groupId>
|
||||
<artifactId>testng</artifactId>
|
||||
<version>RELEASE</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.13.2</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package com.baeldung.floatdoubleconversions;
|
||||
|
||||
public class FloatAndDoubleConversions {
|
||||
public static void main(String args[]){
|
||||
float vatRate = 14.432511f;
|
||||
System.out.println("vatRate:"+vatRate);
|
||||
Float localTaxRate = 20.12434f;
|
||||
System.out.println("localTaxRate:"+localTaxRate);
|
||||
|
||||
double shootingAverage = 56.00000000000001;
|
||||
System.out.println("shootingAverage:"+shootingAverage);
|
||||
Double assistAverage = 81.123000000045;
|
||||
System.out.println("assistAverage:"+assistAverage);
|
||||
}
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
package com.baeldung.floatdoubleconversions;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class FloatDoubleConversionsTest {
|
||||
|
||||
@Test
|
||||
public void whenDoubleType_thenFloatTypeSuccess(){
|
||||
double interestRatesYearly = 13.333333333333334;
|
||||
float interest = (float) interestRatesYearly;
|
||||
System.out.println(interest); //13.333333
|
||||
Assert.assertTrue(Float.class.isInstance(interest));//true
|
||||
|
||||
Double monthlyRates = 2.111111111111112;
|
||||
float rates = monthlyRates.floatValue();
|
||||
System.out.println(rates); //2.1111112
|
||||
Assert.assertTrue(Float.class.isInstance(rates));//true
|
||||
}
|
||||
@Test
|
||||
public void whenFloatType_thenDoubleTypeSuccess(){
|
||||
float gradeAverage =2.05f;
|
||||
double average = gradeAverage;
|
||||
System.out.println(average); //2.049999952316284
|
||||
Assert.assertTrue(Double.class.isInstance(average));//true
|
||||
|
||||
Float monthlyRates = 2.1111112f;
|
||||
Double rates = monthlyRates.doubleValue();
|
||||
System.out.println(rates); //2.1111112
|
||||
Assert.assertTrue(Double.class.isInstance(rates));//true
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
*.class
|
||||
|
||||
0.*
|
||||
|
||||
#folders#
|
||||
/target
|
||||
/neoDb*
|
||||
/data
|
||||
/src/main/webapp/WEB-INF/classes
|
||||
*/META-INF/*
|
||||
.resourceCache
|
||||
|
||||
# Packaged files #
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
||||
|
||||
# Files generated by integration tests
|
||||
*.txt
|
||||
backup-pom.xml
|
||||
/bin/
|
||||
/temp
|
||||
|
||||
#IntelliJ specific
|
||||
.idea/
|
||||
*.iml
|
||||
@@ -0,0 +1,7 @@
|
||||
## Core Java OS
|
||||
|
||||
This module contains articles about working with the operating system (OS) in Java
|
||||
|
||||
### Relevant Articles:
|
||||
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
<?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-os</artifactId>
|
||||
<name>core-java-os</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<build>
|
||||
<finalName>core-java-os</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>${maven.compiler.source}</source>
|
||||
<target>${maven.compiler.target}</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source>1.9</maven.compiler.source>
|
||||
<maven.compiler.target>1.9</maven.compiler.target>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package com.baeldung.system;
|
||||
|
||||
public class EnvironmentExample {
|
||||
public void getUserName() {
|
||||
String username = System.getenv("USERNAME");
|
||||
System.out.println("User: " + username);
|
||||
}
|
||||
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package com.baeldung.system;
|
||||
|
||||
public class PropertiesExample {
|
||||
public void getUserName() {
|
||||
String username = System.getProperty("user.name");
|
||||
System.out.println("User: " + username);
|
||||
}
|
||||
|
||||
public void getCustomProp() {
|
||||
String customProperty = System.getProperty("custom.prop");
|
||||
System.out.println("Custom property: " + customProperty);
|
||||
}
|
||||
|
||||
public void getCustomPropWithFallback() {
|
||||
String customProperty = System.getProperty("non-existent-property", "default value");
|
||||
System.out.println("Custom property: " + customProperty);
|
||||
}
|
||||
|
||||
}
|
||||
-25
@@ -1,25 +0,0 @@
|
||||
package com.baeldung.system;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
|
||||
@Ignore
|
||||
public class WhenDetectingOSUnitTest {
|
||||
|
||||
private DetectOS os = new DetectOS();
|
||||
|
||||
@Test
|
||||
public void whenUsingSystemProperty_shouldReturnOS() {
|
||||
String expected = "Windows 10";
|
||||
String actual = os.getOperatingSystem();
|
||||
Assert.assertEquals(expected, actual);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingSystemUtils_shouldReturnOS() {
|
||||
String expected = "Windows 10";
|
||||
String actual = os.getOperatingSystemSystemUtils();
|
||||
Assert.assertEquals(expected, actual);
|
||||
}
|
||||
}
|
||||
-64
@@ -1,64 +0,0 @@
|
||||
package com.baeldung.system.exit;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.security.Permission;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
@Ignore("This test is ignored because it tests deprecated code")
|
||||
public class SystemExitUnitTest {
|
||||
|
||||
private SecurityManager securityManager;
|
||||
private SystemExitExample example;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
example = new SystemExitExample();
|
||||
securityManager = System.getSecurityManager();
|
||||
System.setSecurityManager(new NoExitSecurityManager());
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() throws Exception {
|
||||
System.setSecurityManager(securityManager);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testExit() throws Exception {
|
||||
try {
|
||||
example.readFile();
|
||||
} catch (ExitException e) {
|
||||
assertEquals("Exit status", 2, e.status);
|
||||
}
|
||||
}
|
||||
|
||||
protected static class ExitException extends SecurityException {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
public final int status;
|
||||
|
||||
public ExitException(int status) {
|
||||
this.status = status;
|
||||
}
|
||||
}
|
||||
|
||||
private static class NoExitSecurityManager extends SecurityManager {
|
||||
@Override
|
||||
public void checkPermission(Permission perm) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void checkPermission(Permission perm, Object context) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void checkExit(int status) {
|
||||
super.checkExit(status);
|
||||
throw new ExitException(status);
|
||||
}
|
||||
}
|
||||
}
|
||||
+91
@@ -0,0 +1,91 @@
|
||||
package com.baeldung.alphanumeric;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import org.openjdk.jmh.annotations.Benchmark;
|
||||
import org.openjdk.jmh.annotations.BenchmarkMode;
|
||||
import org.openjdk.jmh.annotations.Fork;
|
||||
import org.openjdk.jmh.annotations.Measurement;
|
||||
import org.openjdk.jmh.annotations.Mode;
|
||||
import org.openjdk.jmh.annotations.Warmup;
|
||||
import org.openjdk.jmh.infra.Blackhole;
|
||||
|
||||
@Warmup(iterations = 1)
|
||||
@Measurement(iterations = 1, time = 1, timeUnit = TimeUnit.MINUTES)
|
||||
@Fork(1)
|
||||
public class AlphanumericPerformanceBenchmark {
|
||||
|
||||
private static final String TEST_STRING = "ABC123abc123";
|
||||
private static final String REGEX = "[^[a-zA-Z0-9]*$]";
|
||||
private static final Pattern PATTERN = Pattern.compile(REGEX);
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.Throughput)
|
||||
public void alphanumericRegex(Blackhole blackhole) {
|
||||
final Matcher matcher = PATTERN.matcher(TEST_STRING);
|
||||
boolean result = matcher.matches();
|
||||
blackhole.consume(result);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.Throughput)
|
||||
public void alphanumericRegexDirectlyOnString(Blackhole blackhole) {
|
||||
boolean result = TEST_STRING.matches(REGEX);
|
||||
blackhole.consume(result);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.Throughput)
|
||||
public void alphanumericIteration(Blackhole blackhole) {
|
||||
boolean result = true;
|
||||
for (int i = 0; i < TEST_STRING.length(); ++i) {
|
||||
final int codePoint = TEST_STRING.codePointAt(i);
|
||||
if (!isAlphanumeric(codePoint)) {
|
||||
result = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
blackhole.consume(result);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.Throughput)
|
||||
public void alphanumericIterationWithCharacterChecks(Blackhole blackhole) {
|
||||
boolean result = true;
|
||||
for (int i = 0; i < TEST_STRING.length(); ++i) {
|
||||
final int codePoint = TEST_STRING.codePointAt(i);
|
||||
if (!Character.isAlphabetic(codePoint) || !Character.isDigit(codePoint)) {
|
||||
result = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
blackhole.consume(result);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.Throughput)
|
||||
public void alphanumericIterationWithCopy(Blackhole blackhole) {
|
||||
boolean result = true;
|
||||
for (final char c : TEST_STRING.toCharArray()) {
|
||||
if (!isAlphanumeric(c)) {
|
||||
result = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
blackhole.consume(result);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.Throughput)
|
||||
public void alphanumericIterationWithStream(Blackhole blackhole) {
|
||||
boolean result = TEST_STRING.chars().allMatch(this::isAlphanumeric);
|
||||
blackhole.consume(result);
|
||||
}
|
||||
|
||||
public boolean isAlphanumeric(final int codePoint) {
|
||||
return (codePoint >= 65 && codePoint <= 90) ||
|
||||
(codePoint >= 97 && codePoint <= 172) ||
|
||||
(codePoint >= 48 && codePoint <= 57);
|
||||
}
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
package com.baeldung.alphanumeric;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
|
||||
class AlphanumericUnitTest {
|
||||
|
||||
private AlphanumericPerformanceBenchmark alphanumericPerformanceBenchmark = new AlphanumericPerformanceBenchmark();
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({
|
||||
"A,true",
|
||||
"B,true",
|
||||
"C,true",
|
||||
"1,true",
|
||||
"2,true",
|
||||
"3,true",
|
||||
"!,false",
|
||||
"@,false",
|
||||
"#,false",
|
||||
"$,false",
|
||||
"%,false"
|
||||
})
|
||||
void shouldCorrectlyIdentifyAlphanumericCharacterTest(char character, boolean result) {
|
||||
boolean actual = alphanumericPerformanceBenchmark.isAlphanumeric(character);
|
||||
assertEquals(actual, result);
|
||||
}
|
||||
}
|
||||
@@ -11,4 +11,5 @@ This module contains articles about string-related algorithms.
|
||||
- [Find the First Non Repeating Character in a String in Java](https://www.baeldung.com/java-find-the-first-non-repeating-character)
|
||||
- [Find the First Embedded Occurrence of an Integer in a Java String](https://www.baeldung.com/java-string-find-embedded-integer)
|
||||
- [Find the Most Frequent Characters in a String](https://www.baeldung.com/java-string-find-most-frequent-characters)
|
||||
- [Checking If a String Is a Repeated Substring](https://www.baeldung.com/java-repeated-substring)
|
||||
- [Checking If a String Is a Repeated Substring](https://www.baeldung.com/java-repeated-substring)
|
||||
- [Check if Letter Is Emoji With Java](https://www.baeldung.com/java-check-letter-emoji)
|
||||
|
||||
@@ -11,4 +11,3 @@
|
||||
- [Check if the First Letter of a String Is a Number](https://www.baeldung.com/java-check-if-string-starts-with-number)
|
||||
- [Print “” Quotes Around a String in Java](https://www.baeldung.com/java-string-print-quotes)
|
||||
- [Remove Punctuation From a String in Java](https://www.baeldung.com/java-remove-punctuation-from-string)
|
||||
- [Replacing Single Quote with \’ in Java String](https://www.baeldung.com/java-replacing-single-quote-string)
|
||||
|
||||
@@ -10,3 +10,5 @@
|
||||
- [Check if a String Contains Non-Alphanumeric Characters](https://www.baeldung.com/java-string-test-special-characters)
|
||||
- [Check if a String Has All Unique Characters in Java](https://www.baeldung.com/java-check-string-all-unique-chars)
|
||||
- [Performance Comparison Between Different Java String Concatenation Methods](https://www.baeldung.com/java-string-concatenation-methods)
|
||||
- [Replacing Single Quote with \’ in Java String](https://www.baeldung.com/java-replacing-single-quote-string)
|
||||
|
||||
|
||||
@@ -78,6 +78,7 @@
|
||||
<module>core-java-collections-list</module>
|
||||
<module>core-java-collections-list-2</module>
|
||||
<module>core-java-collections-list-3</module>
|
||||
<module>core-java-collections-list-6</module>
|
||||
<module>core-java-collections-maps</module>
|
||||
<module>core-java-collections-maps-2</module>
|
||||
<module>core-java-collections-maps-3</module>
|
||||
@@ -108,6 +109,7 @@
|
||||
<module>core-java-io-2</module>
|
||||
<module>core-java-io-3</module>
|
||||
<module>core-java-io-4</module>
|
||||
<module>core-java-io-5</module>
|
||||
<module>core-java-io-apis</module>
|
||||
<module>core-java-io-apis-2</module>
|
||||
<module>core-java-io-conversions</module>
|
||||
|
||||
Reference in New Issue
Block a user