Merge branch 'eugenp:master' into master
This commit is contained in:
+102
@@ -0,0 +1,102 @@
|
||||
package com.baeldung.algorithms.rotatearray;
|
||||
|
||||
/**
|
||||
* To speed up the rotation, we narrow k rotations to the remainder of k divided by the array length, or k module the array length.
|
||||
* Therefore, a large rotation number will be translated into the relative smallest rotation.
|
||||
* All solutions replace the original array, although they might use an extra array to compute the rotation.
|
||||
*/
|
||||
public class RotateArray {
|
||||
|
||||
private RotateArray() {
|
||||
throw new IllegalStateException("Rotate array algorithm utility methods class");
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param arr array to apply rotation to
|
||||
* @param k number of rotations
|
||||
*/
|
||||
public static void bruteForce(int[] arr, int k) {
|
||||
checkInvalidInput(arr, k);
|
||||
|
||||
k %= arr.length;
|
||||
int temp;
|
||||
int previous;
|
||||
for (int i = 0; i < k; i++) {
|
||||
previous = arr[arr.length - 1];
|
||||
for (int j = 0; j < arr.length; j++) {
|
||||
temp = arr[j];
|
||||
arr[j] = previous;
|
||||
previous = temp;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param arr array to apply rotation to
|
||||
* @param k number of rotations
|
||||
*/
|
||||
public static void withExtraArray(int[] arr, int k) {
|
||||
checkInvalidInput(arr, k);
|
||||
|
||||
int[] extraArray = new int[arr.length];
|
||||
for (int i = 0; i < arr.length; i++) {
|
||||
extraArray[(i + k) % arr.length] = arr[i];
|
||||
}
|
||||
System.arraycopy(extraArray, 0, arr, 0, arr.length);
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param arr array to apply rotation to
|
||||
* @param k number of rotations
|
||||
*/
|
||||
public static void cyclicReplacement(int[] arr, int k) {
|
||||
checkInvalidInput(arr, k);
|
||||
|
||||
k = k % arr.length;
|
||||
int count = 0;
|
||||
for (int start = 0; count < arr.length; start++) {
|
||||
int current = start;
|
||||
int prev = arr[start];
|
||||
do {
|
||||
int next = (current + k) % arr.length;
|
||||
int temp = arr[next];
|
||||
arr[next] = prev;
|
||||
prev = temp;
|
||||
current = next;
|
||||
count++;
|
||||
} while (start != current);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param arr array to apply rotation to
|
||||
* @param k number of rotations
|
||||
*/
|
||||
public static void reverse(int[] arr, int k) {
|
||||
checkInvalidInput(arr, k);
|
||||
|
||||
k %= arr.length;
|
||||
reverse(arr, 0, arr.length - 1);
|
||||
reverse(arr, 0, k - 1);
|
||||
reverse(arr, k, arr.length - 1);
|
||||
}
|
||||
|
||||
private static void reverse(int[] nums, int start, int end) {
|
||||
while (start < end) {
|
||||
int temp = nums[start];
|
||||
nums[start] = nums[end];
|
||||
nums[end] = temp;
|
||||
start++;
|
||||
end--;
|
||||
}
|
||||
}
|
||||
|
||||
private static void checkInvalidInput(int[] arr, int rotation) {
|
||||
if (rotation < 1 || arr == null)
|
||||
throw new IllegalArgumentException("Rotation must be greater than zero or array must be not null");
|
||||
}
|
||||
}
|
||||
+124
@@ -0,0 +1,124 @@
|
||||
package com.baeldung.algorithms.rotatearray;
|
||||
|
||||
import static com.baeldung.algorithms.rotatearray.RotateArray.bruteForce;
|
||||
import static com.baeldung.algorithms.rotatearray.RotateArray.cyclicReplacement;
|
||||
import static com.baeldung.algorithms.rotatearray.RotateArray.reverse;
|
||||
import static com.baeldung.algorithms.rotatearray.RotateArray.withExtraArray;
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class RotateArrayUnitTest {
|
||||
|
||||
private final int[] arr = { 1, 2, 3, 4, 5, 6 };
|
||||
private final int rotationLtArrayLength = 1;
|
||||
private final int rotationGtArrayLength = arr.length + 2;
|
||||
private final int[] ltArrayLengthRotation = { 6, 1, 2, 3, 4, 5 };
|
||||
private final int[] gtArrayLengthRotation = { 5, 6, 1, 2, 3, 4 };
|
||||
|
||||
@Test
|
||||
void givenInputArray_whenNoRotationOrEmptyArray_thenThrowIllegalArgumentException() {
|
||||
final int noRotation = 0;
|
||||
final int someRotation = arr.length - 1;
|
||||
|
||||
assertThrows(IllegalArgumentException.class, () -> bruteForce(arr, noRotation));
|
||||
assertThrows(IllegalArgumentException.class, () -> withExtraArray(arr, noRotation));
|
||||
assertThrows(IllegalArgumentException.class, () -> cyclicReplacement(arr, noRotation));
|
||||
assertThrows(IllegalArgumentException.class, () -> reverse(arr, noRotation));
|
||||
|
||||
assertThrows(IllegalArgumentException.class, () -> bruteForce(null, someRotation));
|
||||
assertThrows(IllegalArgumentException.class, () -> withExtraArray(null, someRotation));
|
||||
assertThrows(IllegalArgumentException.class, () -> cyclicReplacement(null, someRotation));
|
||||
assertThrows(IllegalArgumentException.class, () -> reverse(null, someRotation));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenInputArray_whenUseBruteForceRotationLtArrayLength_thenRotateArrayOk() {
|
||||
|
||||
bruteForce(arr, rotationLtArrayLength);
|
||||
assertArrayEquals(ltArrayLengthRotation, arr);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenInputArray_whenUseBruteForceRotationGtArrayLength_thenRotateArrayOk() {
|
||||
|
||||
bruteForce(arr, rotationGtArrayLength);
|
||||
assertArrayEquals(gtArrayLengthRotation, arr);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenInputArray_whenUseBruteForceRotationEqArrayLength_thenDoNothing() {
|
||||
int[] expected = arr.clone();
|
||||
|
||||
bruteForce(arr, arr.length);
|
||||
assertArrayEquals(expected, arr);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenInputArray_whenUseExtraArrayRotationLtArrayLength_thenRotateArrayOk() {
|
||||
|
||||
withExtraArray(arr, rotationLtArrayLength);
|
||||
assertArrayEquals(ltArrayLengthRotation, arr);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenInputArray_whenUseExtraArrayRotationGtArrayLength_thenRotateArrayOk() {
|
||||
|
||||
withExtraArray(arr, rotationGtArrayLength);
|
||||
assertArrayEquals(gtArrayLengthRotation, arr);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenInputArray_whenUseExtraArrayWithRotationEqArrayLength_thenDoNothing() {
|
||||
int[] clone = arr.clone();
|
||||
|
||||
withExtraArray(arr, arr.length);
|
||||
assertArrayEquals(clone, arr);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenInputArray_whenUseCyclicReplacementRotationLtArrayLength_thenRotateArrayOk() {
|
||||
|
||||
cyclicReplacement(arr, rotationLtArrayLength);
|
||||
assertArrayEquals(ltArrayLengthRotation, arr);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenInputArray_whenUseCyclicReplacementRotationGtArrayLength_thenRotateArrayOk() {
|
||||
|
||||
cyclicReplacement(arr, rotationGtArrayLength);
|
||||
assertArrayEquals(gtArrayLengthRotation, arr);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenInputArray_whenUseCyclicReplacementRotationEqArrayLength_thenDoNothing() {
|
||||
int[] clone = arr.clone();
|
||||
|
||||
cyclicReplacement(arr, arr.length);
|
||||
assertArrayEquals(clone, arr);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenInputArray_whenUseReverseRotationLtArrayLength_thenRotateArrayOk() {
|
||||
|
||||
reverse(arr, rotationLtArrayLength);
|
||||
assertArrayEquals(ltArrayLengthRotation, arr);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenInputArray_whenUseReverseRotationGtArrayLength_thenRotateArrayOk() {
|
||||
|
||||
reverse(arr, rotationGtArrayLength);
|
||||
assertArrayEquals(gtArrayLengthRotation, arr);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenInputArray_whenUseReverseRotationEqArrayLength_thenDoNothing() {
|
||||
|
||||
int[] clone = arr.clone();
|
||||
|
||||
reverse(arr, arr.length);
|
||||
assertArrayEquals(clone, arr);
|
||||
}
|
||||
}
|
||||
@@ -13,3 +13,4 @@ You can build the project from the command line using: *mvn clean install*, or i
|
||||
- [Read Data From the Beginning Using Kafka Consumer API](https://www.baeldung.com/java-kafka-consumer-api-read)
|
||||
- [Get Partition Count for a Topic in Kafka](https://www.baeldung.com/java-kafka-partition-count-topic)
|
||||
- [bootstrap-server in Kafka Configuration](https://www.baeldung.com/java-kafka-bootstrap-server)
|
||||
- [Introduction to Apache Kafka](https://www.baeldung.com/apache-kafka)
|
||||
|
||||
+103
@@ -0,0 +1,103 @@
|
||||
package com.baeldung.kafka.multipletopics;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.Arrays;
|
||||
import java.util.Properties;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
|
||||
import org.apache.kafka.clients.consumer.ConsumerConfig;
|
||||
import org.apache.kafka.clients.consumer.ConsumerRecord;
|
||||
import org.apache.kafka.clients.consumer.KafkaConsumer;
|
||||
import org.apache.kafka.clients.producer.KafkaProducer;
|
||||
import org.apache.kafka.clients.producer.ProducerConfig;
|
||||
import org.apache.kafka.clients.producer.ProducerRecord;
|
||||
import org.apache.kafka.common.serialization.StringDeserializer;
|
||||
import org.apache.kafka.common.serialization.StringSerializer;
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.testcontainers.containers.KafkaContainer;
|
||||
import org.testcontainers.junit.jupiter.Container;
|
||||
import org.testcontainers.junit.jupiter.Testcontainers;
|
||||
import org.testcontainers.utility.DockerImageName;
|
||||
|
||||
// This live test needs a Docker Daemon running so that a kafka container can be created
|
||||
|
||||
@Testcontainers
|
||||
public class MultipleTopicsLiveTest {
|
||||
|
||||
private final Logger log = LoggerFactory.getLogger(MultipleTopicsLiveTest.class);
|
||||
|
||||
private static final String CARD_PAYMENTS_TOPIC = "card-payments";
|
||||
private static final String BANK_TRANSFERS_TOPIC = "bank-transfers";
|
||||
private static KafkaProducer<String, String> producer;
|
||||
private static KafkaConsumer<String, String> consumer;
|
||||
|
||||
@Container
|
||||
private static final KafkaContainer KAFKA_CONTAINER = new KafkaContainer(DockerImageName.parse("confluentinc/cp-kafka:latest"));
|
||||
|
||||
@BeforeAll
|
||||
static void setup() {
|
||||
KAFKA_CONTAINER.addExposedPort(9092);
|
||||
producer = new KafkaProducer<>(getProducerProperties());
|
||||
consumer = new KafkaConsumer<>(getConsumerProperties());
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
static void destroy() {
|
||||
KAFKA_CONTAINER.stop();
|
||||
}
|
||||
|
||||
private static Properties getProducerProperties() {
|
||||
Properties producerProperties = new Properties();
|
||||
producerProperties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, KAFKA_CONTAINER.getBootstrapServers());
|
||||
producerProperties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
|
||||
producerProperties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
|
||||
return producerProperties;
|
||||
}
|
||||
|
||||
private static Properties getConsumerProperties() {
|
||||
Properties consumerProperties = new Properties();
|
||||
consumerProperties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, KAFKA_CONTAINER.getBootstrapServers());
|
||||
consumerProperties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
|
||||
consumerProperties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
|
||||
consumerProperties.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
|
||||
consumerProperties.put(ConsumerConfig.GROUP_ID_CONFIG, "payments");
|
||||
return consumerProperties;
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenSendingMessagesOnTwoTopics_thenConsumerReceivesMessages() throws Exception {
|
||||
publishMessages();
|
||||
|
||||
consumer.subscribe(Arrays.asList(CARD_PAYMENTS_TOPIC, BANK_TRANSFERS_TOPIC));
|
||||
|
||||
int eventsProcessed = 0;
|
||||
for (ConsumerRecord<String, String> record : consumer.poll(Duration.ofSeconds(10))) {
|
||||
log.info("Event on topic={}, payload={}", record.topic(), record.value());
|
||||
eventsProcessed++;
|
||||
}
|
||||
|
||||
assertThat(eventsProcessed).isEqualTo(2);
|
||||
}
|
||||
|
||||
private void publishMessages() throws ExecutionException, InterruptedException {
|
||||
ProducerRecord<String, String> cardPayment = new ProducerRecord<>(CARD_PAYMENTS_TOPIC, createCardPayment());
|
||||
producer.send(cardPayment).get();
|
||||
|
||||
ProducerRecord<String, String> bankTransfer = new ProducerRecord<>(BANK_TRANSFERS_TOPIC, createBankTransfer());
|
||||
producer.send(bankTransfer).get();
|
||||
}
|
||||
|
||||
private String createCardPayment() {
|
||||
return "{\"paymentReference\":\"A184028KM0013790\", \"type\":\"card\", \"amount\":\"275\", \"currency\":\"GBP\"}";
|
||||
}
|
||||
|
||||
private String createBankTransfer() {
|
||||
return "{\"paymentReference\":\"19ae2-18mk73-009\", \"type\":\"bank\", \"amount\":\"150\", \"currency\":\"EUR\"}";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
## Relevant Articles
|
||||
- [How To Convert Excel Data Into List Of Java Objects](https://www.baeldung.com/java-convert-excel-data-into-list)
|
||||
- [Expand Columns with Apache POI](https://www.baeldung.com/java-apache-poi-expand-columns)
|
||||
@@ -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)
|
||||
|
||||
@@ -30,6 +30,11 @@ public final class Point {
|
||||
return new Point(x, y, z);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Point{" + "x=" + x + ", y=" + y + ", z=" + z + '}';
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object other) {
|
||||
if (other == null || getClass() != other.getClass())
|
||||
|
||||
+6
-3
@@ -1,14 +1,17 @@
|
||||
package com.baeldung.value_based_class;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class ValueBasedClassUnitTest {
|
||||
@Test
|
||||
public void givenAutoboxedAndPrimitive_whenCompared_thenReturnEquals() {
|
||||
int primitive_a = 125;
|
||||
Integer obj_a = 125; // this is autoboxed
|
||||
Assert.assertSame(primitive_a, obj_a);
|
||||
List<Integer> list = new ArrayList<>();
|
||||
list.add(1); // this is autoboxed
|
||||
Assert.assertEquals(list.get(0), Integer.valueOf(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
<?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-18</artifactId>
|
||||
<name>core-java-18</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<relativePath>../../</relativePath>
|
||||
</parent>
|
||||
|
||||
<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>
|
||||
<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>18</maven.compiler.source.version>
|
||||
<maven.compiler.target.version>18</maven.compiler.target.version>
|
||||
<maven.compiler.release>18</maven.compiler.release>
|
||||
<surefire.plugin.version>3.0.0-M5</surefire.plugin.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
package com.baeldung.finalization_closeable_cleaner;
|
||||
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
|
||||
public class FinalizationExamples {
|
||||
FileInputStream fis = null;
|
||||
|
||||
public void readFileOperationWithFinalization() throws IOException {
|
||||
try {
|
||||
fis = new FileInputStream("input.txt");
|
||||
// perform operation on the file
|
||||
System.out.println(fis.readAllBytes().length);
|
||||
|
||||
} finally {
|
||||
if (fis != null)
|
||||
fis.close();
|
||||
}
|
||||
}
|
||||
|
||||
public void readFileOperationWithTryWith() throws IOException {
|
||||
try (FileInputStream fis = new FileInputStream("input.txt")) {
|
||||
// perform operations
|
||||
System.out.println(fis.readAllBytes().length);
|
||||
}
|
||||
}
|
||||
}
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
package com.baeldung.finalization_closeable_cleaner;
|
||||
|
||||
import java.lang.ref.Cleaner;
|
||||
|
||||
public class MyCleanerResourceClass implements AutoCloseable {
|
||||
private static Resource resource;
|
||||
|
||||
private static final Cleaner cleaner = Cleaner.create();
|
||||
private final Cleaner.Cleanable cleanable;
|
||||
|
||||
public MyCleanerResourceClass() {
|
||||
resource = new Resource();
|
||||
this.cleanable = cleaner.register(this, new CleaningState());
|
||||
}
|
||||
|
||||
public void useResource() {
|
||||
// using the resource here
|
||||
resource.use();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
// perform actions to close all underlying resources
|
||||
this.cleanable.clean();
|
||||
}
|
||||
|
||||
static class CleaningState implements Runnable {
|
||||
CleaningState() {
|
||||
// constructor
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
// some cleanup action
|
||||
System.out.println("Cleanup done");
|
||||
}
|
||||
}
|
||||
|
||||
static class Resource {
|
||||
void use() {
|
||||
System.out.println("Using the resource");
|
||||
}
|
||||
|
||||
void close() {
|
||||
System.out.println("Cleanup done");
|
||||
}
|
||||
}
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package com.baeldung.finalization_closeable_cleaner;
|
||||
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.IOException;
|
||||
|
||||
public class MyCloseableResourceClass implements AutoCloseable {
|
||||
|
||||
private final FileInputStream fis;
|
||||
|
||||
public MyCloseableResourceClass() throws FileNotFoundException {
|
||||
this.fis = new FileInputStream("src/main/resources/file.txt");
|
||||
|
||||
}
|
||||
|
||||
public int getByteLength() throws IOException {
|
||||
System.out.println("Some operation");
|
||||
return this.fis.readAllBytes().length;
|
||||
}
|
||||
@Override
|
||||
public void close() throws IOException {
|
||||
System.out.println("Finalized object");
|
||||
this.fis.close();
|
||||
}
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package com.baeldung.finalization_closeable_cleaner;
|
||||
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.IOException;
|
||||
|
||||
public class MyFinalizableResourceClass {
|
||||
private FileInputStream fis;
|
||||
|
||||
public MyFinalizableResourceClass() throws FileNotFoundException {
|
||||
this.fis = new FileInputStream("src/main/resources/file.txt");
|
||||
}
|
||||
|
||||
public int getByteLength() throws IOException {
|
||||
System.out.println("Some operation");
|
||||
return this.fis.readAllBytes().length;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void finalize() throws Throwable {
|
||||
System.out.println("Finalized object");
|
||||
this.fis.close();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
This is a test file.
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
package com.baeldung.finalization_closeable_cleaner;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class FinalizationCloseableCleanerUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenMyFinalizationResource_whenUsingFinalize_thenShouldClean() {
|
||||
assertDoesNotThrow(() -> {
|
||||
MyFinalizableResourceClass mfr = new MyFinalizableResourceClass();
|
||||
mfr.getByteLength();
|
||||
});
|
||||
}
|
||||
@Test
|
||||
public void givenMyCleanerResource_whenUsingCleanerAPI_thenShouldClean() {
|
||||
assertDoesNotThrow(() -> {
|
||||
try (MyCleanerResourceClass myCleanerResourceClass = new MyCleanerResourceClass()) {
|
||||
myCleanerResourceClass.useResource();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCloseableResource_whenUsingTryWith_thenShouldClose() throws IOException {
|
||||
int length = 0;
|
||||
try (MyCloseableResourceClass mcr = new MyCloseableResourceClass()) {
|
||||
length = mcr.getByteLength();
|
||||
}
|
||||
Assert.assertEquals(20, length);
|
||||
}
|
||||
}
|
||||
@@ -1,2 +1,5 @@
|
||||
## Relevant Articles
|
||||
- [Sequenced Collections in Java 21](https://www.baeldung.com/java-21-sequenced-collections)
|
||||
- [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)
|
||||
- [Unnamed Classes and Instance Main Methods in Java 21](https://www.baeldung.com/java-21-unnamed-class-instance-main)
|
||||
- [Unnamed Patterns and Variables in Java 21](https://www.baeldung.com/java-unnamed-patterns-variables)
|
||||
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
void main() {
|
||||
System.out.println("Hello, World!");
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
package com.baeldung.unnamedclasses;
|
||||
|
||||
public class HelloWorldChild extends HelloWorldSuper {
|
||||
void main() {
|
||||
System.out.println("Hello, World!");
|
||||
}
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
package com.baeldung.unnamedclasses;
|
||||
|
||||
public class HelloWorldSuper {
|
||||
public static void main(String[] args) {
|
||||
System.out.println("Hello from the superclass");
|
||||
}
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
private String getMessage() {
|
||||
return "Hello, World!";
|
||||
}
|
||||
void main() {
|
||||
System.out.println(getMessage());
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
package com.baeldung.array.conversions;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
public class CharArrayToIntArrayUtils {
|
||||
|
||||
static int[] usingGetNumericValueMethod(char[] chars) {
|
||||
if (chars == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
int[] ints = new int[chars.length];
|
||||
for (int i = 0; i < chars.length; i++) {
|
||||
ints[i] = Character.getNumericValue(chars[i]);
|
||||
}
|
||||
|
||||
return ints;
|
||||
}
|
||||
|
||||
static int[] usingDigitMethod(char[] chars) {
|
||||
if (chars == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
int[] ints = new int[chars.length];
|
||||
for (int i = 0; i < chars.length; i++) {
|
||||
ints[i] = Character.digit(chars[i], 10);
|
||||
}
|
||||
|
||||
return ints;
|
||||
}
|
||||
|
||||
static int[] usingStreamApiMethod(char[] chars) {
|
||||
if (chars == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return new String(chars).chars()
|
||||
.map(c -> c - 48)
|
||||
.toArray();
|
||||
}
|
||||
|
||||
static int[] usingParseIntMethod(char[] chars) {
|
||||
if (chars == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
int[] ints = new int[chars.length];
|
||||
for (int i = 0; i < chars.length; i++) {
|
||||
ints[i] = Integer.parseInt(String.valueOf(chars[i]));
|
||||
}
|
||||
|
||||
return ints;
|
||||
}
|
||||
|
||||
static int[] usingArraysSetAllMethod(char[] chars) {
|
||||
if (chars == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
int[] ints = new int[chars.length];
|
||||
Arrays.setAll(ints, i -> Character.getNumericValue(chars[i]));
|
||||
|
||||
return ints;
|
||||
}
|
||||
|
||||
}
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
package com.baeldung.array.conversions;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class CharArrayToIntArrayUtilsUnitTest {
|
||||
|
||||
@Test
|
||||
void givenCharArray_whenUsingGetNumericValueMethod_shouldGetIntArray() {
|
||||
int[] expected = { 2, 3, 4, 5 };
|
||||
char[] chars = { '2', '3', '4', '5' };
|
||||
int[] result = CharArrayToIntArrayUtils.usingGetNumericValueMethod(chars);
|
||||
|
||||
assertArrayEquals(expected, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenCharArray_whenUsingDigitMethod_shouldGetIntArray() {
|
||||
int[] expected = { 1, 2, 3, 6 };
|
||||
char[] chars = { '1', '2', '3', '6' };
|
||||
int[] result = CharArrayToIntArrayUtils.usingDigitMethod(chars);
|
||||
|
||||
assertArrayEquals(expected, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenCharArray_whenUsingStreamApi_shouldGetIntArray() {
|
||||
int[] expected = { 9, 8, 7, 6 };
|
||||
char[] chars = { '9', '8', '7', '6' };
|
||||
int[] result = CharArrayToIntArrayUtils.usingStreamApiMethod(chars);
|
||||
|
||||
assertArrayEquals(expected, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenCharArray_whenUsingParseIntMethod_shouldGetIntArray() {
|
||||
int[] expected = { 9, 8, 7, 6 };
|
||||
char[] chars = { '9', '8', '7', '6' };
|
||||
int[] result = CharArrayToIntArrayUtils.usingParseIntMethod(chars);
|
||||
|
||||
assertArrayEquals(expected, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenCharArray_whenUsingArraysSetAllMethod_shouldGetIntArray() {
|
||||
int[] expected = { 4, 9, 2, 3 };
|
||||
char[] chars = { '4', '9', '2', '3' };
|
||||
int[] result = CharArrayToIntArrayUtils.usingArraysSetAllMethod(chars);
|
||||
|
||||
assertArrayEquals(expected, result);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
@@ -5,3 +5,4 @@ This module contains articles about Java Character Class
|
||||
### Relevant Articles:
|
||||
- [Character#isAlphabetic vs. Character#isLetter](https://www.baeldung.com/java-character-isletter-isalphabetic)
|
||||
- [Difference Between Java’s “char” and “String”](https://www.baeldung.com/java-char-vs-string)
|
||||
- [Increment Character in Java](https://www.baeldung.com/java-char-sequence)
|
||||
|
||||
@@ -5,4 +5,6 @@
|
||||
### Relevant Articles:
|
||||
- [Introduction to Roaring Bitmap](https://www.baeldung.com/java-roaring-bitmap-intro)
|
||||
- [Creating Custom Iterator in Java](https://www.baeldung.com/java-creating-custom-iterator)
|
||||
- [Difference Between Arrays.sort() and Collections.sort()](https://www.baeldung.com/java-arrays-collections-sort-methods)
|
||||
- [Skipping the First Iteration in Java](https://www.baeldung.com/java-skip-first-iteration)
|
||||
- More articles: [[<-- prev]](/core-java-modules/core-java-collections-4)
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
## Core Java Collections ArrayList
|
||||
|
||||
This module contains articles about the Java ArrayList collection
|
||||
|
||||
### Relevant Articles:
|
||||
- [Create an ArrayList with Multiple Object Types](https://www.baeldung.com/java-arraylist-multiple-object-types)
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user