Merge remote-tracking branch 'origin/PR-7005' into PR-7005
This commit is contained in:
commit
b3894f1e85
|
@ -0,0 +1,32 @@
|
|||
---
|
||||
name: Issue Report
|
||||
about: Report an issue to help us improve
|
||||
title: '[ISSUE] '
|
||||
---
|
||||
|
||||
**Article and Module Links**
|
||||
A link to the affected article and the affected module. You can find the link to the module in the Conclusion section in the "on Github" standard phase.
|
||||
|
||||
**Describe the Issue**
|
||||
A clear and concise description of what the issue is.
|
||||
|
||||
**To Reproduce**
|
||||
Steps to reproduce the behavior:
|
||||
1. Go to '...'
|
||||
2. Click on '....'
|
||||
3. Scroll down to '....'
|
||||
4. See error
|
||||
|
||||
**Expected Behavior**
|
||||
A clear and concise description of what you expected to happen.
|
||||
|
||||
**Screenshots**
|
||||
If applicable, add screenshots to help explain your problem.
|
||||
|
||||
**Environment (please complete the following information):**
|
||||
- OS: [e.g. Windows]
|
||||
- Browser [e.g. chrome, safari]
|
||||
- Version [e.g. 22]
|
||||
|
||||
**Additional Context**
|
||||
Add any other context about the issue here.
|
|
@ -0,0 +1,11 @@
|
|||
# Contributing to Baeldung Tutorials
|
||||
First off, thank you for considering contributing to Baeldung Tutorials.
|
||||
|
||||
## Reporting Issues
|
||||
Before you submit an issue, please review the guidelines below:
|
||||
|
||||
1. **No Custom Modifications:** If your issue arises from any custom modifications you've made to the code in the repository, we won't be able to assist. We can only help if the issue is reproducible with the untouched codebase from this repo. If you're working with a modified version, consider asking for help on StackOverflow or other relevant forums.
|
||||
2. **Use a clear and descriptive title** for the issue to identify the problem.
|
||||
3. **Include a link to the article** you're having issues with.
|
||||
4. **Describe the exact steps which reproduce the problem** in as many details as possible.
|
||||
5. **Additional Details:** Offer any other context or descriptions that could be useful. Screenshots, error messages, copy/pasteable snippets, or logs can be immensely helpful.
|
|
@ -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");
|
||||
}
|
||||
}
|
|
@ -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)
|
||||
|
|
|
@ -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)
|
|
@ -0,0 +1,97 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
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>apache-poi-3</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>apache-poi-3</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.poi</groupId>
|
||||
<artifactId>poi-ooxml</artifactId>
|
||||
<version>${poi.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.poi</groupId>
|
||||
<artifactId>poi-scratchpad</artifactId>
|
||||
<version>${poi.version}</version>
|
||||
</dependency>
|
||||
<!-- https://mvnrepository.com/artifact/com.github.ozlerhakan/poiji -->
|
||||
<dependency>
|
||||
<groupId>com.github.ozlerhakan</groupId>
|
||||
<artifactId>poiji</artifactId>
|
||||
<version>${poiji.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi/5.2.3 -->
|
||||
<dependency>
|
||||
<groupId>org.apache.poi</groupId>
|
||||
<artifactId>poi</artifactId>
|
||||
<version>${poi.version}</version>
|
||||
</dependency>
|
||||
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml-schemas/4.1.2 -->
|
||||
<dependency>
|
||||
<groupId>org.apache.poi</groupId>
|
||||
<artifactId>poi-ooxml-schemas</artifactId>
|
||||
<version>4.1.2</version>
|
||||
</dependency>
|
||||
<!-- https://mvnrepository.com/artifact/org.apache.xmlbeans/xmlbeans/5.1.1 -->
|
||||
<dependency>
|
||||
<groupId>org.apache.xmlbeans</groupId>
|
||||
<artifactId>xmlbeans</artifactId>
|
||||
<version>5.1.1</version>
|
||||
</dependency>
|
||||
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-collections4 -->
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-collections4</artifactId>
|
||||
<version>4.4</version>
|
||||
</dependency>
|
||||
<!-- https://mvnrepository.com/artifact/org.dhatim/fastexcel/0.15.7 -->
|
||||
<dependency>
|
||||
<groupId>org.dhatim</groupId>
|
||||
<artifactId>fastexcel</artifactId>
|
||||
<version>${fastexcel.version}</version>
|
||||
</dependency>
|
||||
<!-- https://mvnrepository.com/artifact/org.dhatim/fastexcel-reader/0.15.7 -->
|
||||
<dependency>
|
||||
<groupId>org.dhatim</groupId>
|
||||
<artifactId>fastexcel-reader</artifactId>
|
||||
<version>${fastexcel.version}</version>
|
||||
</dependency>
|
||||
<!-- https://mvnrepository.com/artifact/net.sourceforge.jexcelapi/jxl/2.6.12 -->
|
||||
<dependency>
|
||||
<groupId>net.sourceforge.jexcelapi</groupId>
|
||||
<artifactId>jxl</artifactId>
|
||||
<version>${jxl.version}</version>
|
||||
</dependency>
|
||||
<!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-api -->
|
||||
<dependency>
|
||||
<groupId>org.apache.logging.log4j</groupId>
|
||||
<artifactId>log4j-api</artifactId>
|
||||
<version>2.17.1</version>
|
||||
</dependency>
|
||||
<!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core -->
|
||||
<dependency>
|
||||
<groupId>org.apache.logging.log4j</groupId>
|
||||
<artifactId>log4j-core</artifactId>
|
||||
<version>2.17.1</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<poi.version>5.2.3</poi.version>
|
||||
<poiji.version>4.1.1</poiji.version>
|
||||
<fastexcel.version>0.15.7</fastexcel.version>
|
||||
<jxl.version>2.6.12</jxl.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,54 @@
|
|||
package com.baeldung.convert.exceldatatolist;
|
||||
|
||||
import com.poiji.annotation.ExcelCellName;
|
||||
|
||||
public class FoodInfo {
|
||||
|
||||
@ExcelCellName("Category")
|
||||
private String category; //food category
|
||||
@ExcelCellName("Name")
|
||||
private String name; // food name
|
||||
@ExcelCellName("Measure")
|
||||
private String measure;
|
||||
@ExcelCellName("Calories")
|
||||
private double calories; //amount of calories in kcal/measure
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "FoodInfo{" + "category='" + category + '\'' + ", name='" + name + '\'' + ", measure='" + measure + '\'' + ", calories=" + calories + "} \n";
|
||||
}
|
||||
|
||||
|
||||
public String getCategory() {
|
||||
return category;
|
||||
}
|
||||
|
||||
public void setCategory(String category) {
|
||||
this.category = category;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getMeasure() {
|
||||
return measure;
|
||||
}
|
||||
|
||||
public void setMeasure(String measure) {
|
||||
this.measure = measure;
|
||||
}
|
||||
|
||||
public double getCalories() {
|
||||
return calories;
|
||||
}
|
||||
|
||||
public void setCalories(double calories) {
|
||||
this.calories = calories;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,42 @@
|
|||
package com.baeldung.convert.exceldatatolist.fastexcel;
|
||||
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import org.dhatim.fastexcel.reader.ReadableWorkbook;
|
||||
import org.dhatim.fastexcel.reader.Row;
|
||||
import org.dhatim.fastexcel.reader.Sheet;
|
||||
|
||||
import com.baeldung.convert.exceldatatolist.FoodInfo;
|
||||
|
||||
public class ExcelDataToListOfObjectsFastExcel {
|
||||
public static List<FoodInfo> excelDataToListOfObjets_withFastExcel(String fileLocation)throws IOException, NumberFormatException {
|
||||
List<FoodInfo> foodData = new ArrayList<FoodInfo>();
|
||||
|
||||
try (FileInputStream file = new FileInputStream(fileLocation);
|
||||
ReadableWorkbook wb = new ReadableWorkbook(file)) {
|
||||
Sheet sheet = wb.getFirstSheet();
|
||||
for (Row row:
|
||||
sheet.read()
|
||||
) {
|
||||
if(row.getRowNum() == 1) {
|
||||
continue;
|
||||
}
|
||||
FoodInfo food = new FoodInfo();
|
||||
food.setCategory(row.getCellText(0));
|
||||
food.setName(row.getCellText(1));
|
||||
food.setMeasure(row.getCellText(2));
|
||||
food.setCalories(Double.parseDouble(row.getCellText(3)));
|
||||
|
||||
foodData.add(food);
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
return foodData;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,37 @@
|
|||
package com.baeldung.convert.exceldatatolist.jexcelapi;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import com.baeldung.convert.exceldatatolist.FoodInfo;
|
||||
|
||||
import jxl.Sheet;
|
||||
import jxl.Workbook;
|
||||
import jxl.read.biff.BiffException;
|
||||
|
||||
public class ExcelDataToListOfObjectsJxl {
|
||||
public static List<FoodInfo> excelDataToListOfObjets_withJxl(String fileLocation) throws IOException, BiffException {
|
||||
|
||||
List<FoodInfo> foodData = new ArrayList<FoodInfo>();
|
||||
|
||||
Workbook workbook = Workbook.getWorkbook(new File(fileLocation));
|
||||
Sheet sheet = workbook.getSheet(0);
|
||||
|
||||
int rows = sheet.getRows();
|
||||
|
||||
for (int i = 1; i < rows; i++) {
|
||||
FoodInfo foodInfo = new FoodInfo();
|
||||
|
||||
foodInfo.setCategory(sheet.getCell(0, i).getContents());
|
||||
foodInfo.setName(sheet.getCell(1, i).getContents());
|
||||
foodInfo.setMeasure(sheet.getCell(2, i).getContents());
|
||||
foodInfo.setCalories(Double.parseDouble(sheet.getCell(3, i).getContents()));
|
||||
|
||||
foodData.add(foodInfo);
|
||||
|
||||
}
|
||||
return foodData;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,39 @@
|
|||
package com.baeldung.convert.exceldatatolist.poi;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.apache.poi.ss.usermodel.DataFormatter;
|
||||
import org.apache.poi.ss.usermodel.Row;
|
||||
import org.apache.poi.ss.usermodel.Sheet;
|
||||
import org.apache.poi.ss.usermodel.Workbook;
|
||||
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
||||
|
||||
import com.baeldung.convert.exceldatatolist.FoodInfo;
|
||||
|
||||
public class ExcelDataToListApachePOI {
|
||||
public static List<FoodInfo> excelDataToListOfObjets_withApachePOI(String fileLocation) throws IOException {
|
||||
FileInputStream file = new FileInputStream(new File(fileLocation));
|
||||
Workbook workbook = new XSSFWorkbook(file);
|
||||
Sheet sheet = workbook.getSheetAt(0);
|
||||
List<FoodInfo> foodData = new ArrayList<FoodInfo>();
|
||||
DataFormatter dataFormatter = new DataFormatter();
|
||||
for (int n = 1; n < sheet.getPhysicalNumberOfRows(); n++) {
|
||||
Row row = sheet.getRow(n);
|
||||
FoodInfo foodInfo = new FoodInfo();
|
||||
int i = row.getFirstCellNum();
|
||||
|
||||
foodInfo.setCategory(dataFormatter.formatCellValue(row.getCell(i)));
|
||||
foodInfo.setName(dataFormatter.formatCellValue(row.getCell(++i)));
|
||||
foodInfo.setMeasure(dataFormatter.formatCellValue(row.getCell(++i)));
|
||||
foodInfo.setCalories(Double.parseDouble(dataFormatter.formatCellValue(row.getCell(++i))));
|
||||
|
||||
foodData.add(foodInfo);
|
||||
|
||||
}
|
||||
return foodData;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,13 @@
|
|||
package com.baeldung.convert.exceldatatolist.poiji;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.List;
|
||||
|
||||
import com.baeldung.convert.exceldatatolist.FoodInfo;
|
||||
import com.poiji.bind.Poiji;
|
||||
|
||||
public class ExcelDataToListOfObjectsPOIJI {
|
||||
public static List<FoodInfo> excelDataToListOfObjets_withPOIJI(String fileLocation){
|
||||
return Poiji.fromExcel(new File(fileLocation), FoodInfo.class);
|
||||
}
|
||||
}
|
Binary file not shown.
Binary file not shown.
|
@ -0,0 +1,53 @@
|
|||
package com.baeldung.convert.exceldatatolist;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
|
||||
// import org.junit.jupiter.api.Test;
|
||||
// import static org.junit.jupiter.api.Assertions.*;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.convert.exceldatatolist.fastexcel.ExcelDataToListOfObjectsFastExcel;
|
||||
import com.baeldung.convert.exceldatatolist.jexcelapi.ExcelDataToListOfObjectsJxl;
|
||||
import com.baeldung.convert.exceldatatolist.poi.ExcelDataToListApachePOI;
|
||||
import com.baeldung.convert.exceldatatolist.poiji.ExcelDataToListOfObjectsPOIJI;
|
||||
|
||||
import jxl.read.biff.BiffException;
|
||||
|
||||
public class ExcelDataToListOfObjectsUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenParsingExcelFileWithPOIJI_thenConvertsToList() throws IOException {
|
||||
List<FoodInfo> foodInfoList = ExcelDataToListOfObjectsPOIJI.excelDataToListOfObjets_withPOIJI("src/main/resources/food_info.xlsx");
|
||||
|
||||
assertEquals("Beverages", foodInfoList.get(0).getCategory());
|
||||
assertEquals("Dairy", foodInfoList.get(3).getCategory());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenParsingExcelFileWithApachePOI_thenConvertsToList() throws IOException {
|
||||
List<FoodInfo> foodInfoList = ExcelDataToListApachePOI.excelDataToListOfObjets_withApachePOI("src/main/resources/food_info.xlsx");
|
||||
|
||||
assertEquals("Beverages", foodInfoList.get(0).getCategory());
|
||||
assertEquals("Dairy", foodInfoList.get(3).getCategory());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenParsingExcelFileWithFastExcel_thenConvertsToList() throws IOException {
|
||||
List<FoodInfo> foodInfoList = ExcelDataToListOfObjectsFastExcel.excelDataToListOfObjets_withFastExcel("src/main/resources/food_info.xlsx");
|
||||
|
||||
assertEquals("Beverages", foodInfoList.get(0).getCategory());
|
||||
assertEquals("Dairy", foodInfoList.get(3).getCategory());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenParsingExcelFileWithJxl_thenConvertsToList() throws IOException, BiffException {
|
||||
List<FoodInfo> foodInfoList = ExcelDataToListOfObjectsJxl.excelDataToListOfObjets_withJxl("src/main/resources/food_info.xls");
|
||||
|
||||
assertEquals("Beverages", foodInfoList.get(0).getCategory());
|
||||
assertEquals("Dairy", foodInfoList.get(3).getCategory());
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,70 @@
|
|||
package com.baeldung.poi.excel.expandcolumn;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.apache.poi.ss.usermodel.*;
|
||||
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class ExpandColumnUnitTest {
|
||||
|
||||
private Workbook workbook;
|
||||
private Sheet sheet;
|
||||
|
||||
@BeforeEach
|
||||
void prepareSpreadsheet() {
|
||||
workbook = new XSSFWorkbook();
|
||||
sheet = workbook.createSheet();
|
||||
|
||||
Row headerRow = sheet.createRow(0);
|
||||
Cell headerCell1 = headerRow.createCell(0);
|
||||
headerCell1.setCellValue("Full Name");
|
||||
Cell headerCell2 = headerRow.createCell(1);
|
||||
headerCell2.setCellValue("Abbreviation");
|
||||
|
||||
Row dataRow = sheet.createRow(1);
|
||||
Cell dataCell1 = dataRow.createCell(0);
|
||||
dataCell1.setCellValue("Java Virtual Machine");
|
||||
Cell dataCell2 = dataRow.createCell(1);
|
||||
dataCell2.setCellValue("JVM");
|
||||
|
||||
dataRow = sheet.createRow(2);
|
||||
dataCell1 = dataRow.createCell(0);
|
||||
dataCell1.setCellValue("Java Runtime Environment");
|
||||
dataCell2 = dataRow.createCell(1);
|
||||
dataCell2.setCellValue("JRE");
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenSetColumnWidth_thenColumnSetToTheSpecifiedWidth() {
|
||||
|
||||
Row row = sheet.getRow(2);
|
||||
String cellValue = row.getCell(0).getStringCellValue();
|
||||
int targetWidth = cellValue.length() * 256;
|
||||
|
||||
sheet.setColumnWidth(0, targetWidth);
|
||||
|
||||
assertEquals(targetWidth, sheet.getColumnWidth(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenAutoSizeColumn_thenColumnExpands() {
|
||||
|
||||
int originalWidth = sheet.getColumnWidth(0);
|
||||
|
||||
sheet.autoSizeColumn(0);
|
||||
|
||||
assertThat(sheet.getColumnWidth(0)).isGreaterThan(originalWidth);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void cleanup() throws IOException {
|
||||
workbook.close();
|
||||
}
|
||||
|
||||
}
|
|
@ -4,7 +4,7 @@ This module contains articles about Simple Storage Service (S3) on AWS
|
|||
|
||||
### Relevant articles
|
||||
|
||||
- [AWS S3 with Java](https://www.baeldung.com/aws-s3-java)
|
||||
- [AWS S3 with Java](https://www.baeldung.com/java-aws-s3)
|
||||
- [Multipart Uploads in Amazon S3 with Java](https://www.baeldung.com/aws-s3-multipart-upload)
|
||||
- [Using the JetS3t Java Client With Amazon S3](https://www.baeldung.com/jets3t-amazon-s3)
|
||||
- [Check if a Specified Key Exists in a Given S3 Bucket Using Java](https://www.baeldung.com/java-aws-s3-check-specified-key-exists)
|
||||
|
|
|
@ -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())
|
||||
|
|
|
@ -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>
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -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");
|
||||
}
|
||||
}
|
||||
}
|
|
@ -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();
|
||||
}
|
||||
}
|
|
@ -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.
|
|
@ -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 +1,5 @@
|
|||
## 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)
|
||||
- [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)
|
||||
|
|
|
@ -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>
|
|
@ -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);
|
||||
}
|
||||
}
|
|
@ -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 { }
|
|
@ -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";
|
||||
};
|
||||
}
|
||||
}
|
|
@ -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());
|
||||
}
|
||||
}
|
|
@ -0,0 +1,3 @@
|
|||
void main() {
|
||||
System.out.println("Hello, World!");
|
||||
}
|
|
@ -0,0 +1,7 @@
|
|||
package com.baeldung.unnamedclasses;
|
||||
|
||||
public class HelloWorldChild extends HelloWorldSuper {
|
||||
void main() {
|
||||
System.out.println("Hello, World!");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,7 @@
|
|||
package com.baeldung.unnamedclasses;
|
||||
|
||||
public class HelloWorldSuper {
|
||||
public static void main(String[] args) {
|
||||
System.out.println("Hello from the superclass");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,6 @@
|
|||
private String getMessage() {
|
||||
return "Hello, World!";
|
||||
}
|
||||
void main() {
|
||||
System.out.println(getMessage());
|
||||
}
|
|
@ -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"));
|
||||
}
|
||||
}
|
|
@ -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())
|
||||
);
|
||||
|
||||
}
|
|
@ -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)));
|
||||
}
|
||||
}
|
|
@ -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());
|
||||
}
|
||||
}
|
|
@ -5,4 +5,5 @@
|
|||
- [Parsing Date Strings with Varying Formats](https://www.baeldung.com/java-parsing-dates-many-formats)
|
||||
- [How Many Days Are There in a Particular Month of a Given Year?](https://www.baeldung.com/days-particular-month-given-year)
|
||||
- [Difference Between Instant and LocalDateTime](https://www.baeldung.com/java-instant-vs-localdatetime)
|
||||
- [Add Minutes to a Time String in Java](https://www.baeldung.com/java-string-time-add-mins)
|
||||
- [[<-- Prev]](/core-java-modules/core-java-datetime-java8-1)
|
||||
|
|
|
@ -3,9 +3,11 @@ package com.baeldung.dateapi;
|
|||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.LocalTime;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
|
||||
|
@ -19,7 +21,7 @@ public class JavaDurationUnitTest {
|
|||
LocalTime finalTime = initialTime.plus(Duration.ofSeconds(30));
|
||||
|
||||
long seconds = Duration.between(initialTime, finalTime)
|
||||
.getSeconds();
|
||||
.getSeconds();
|
||||
|
||||
assertThat(seconds).isEqualTo(30);
|
||||
}
|
||||
|
@ -34,6 +36,22 @@ public class JavaDurationUnitTest {
|
|||
assertThat(seconds).isEqualTo(30);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenADuration_whenCallingisZeroAndisNegative_thenGetExpectedResult() {
|
||||
LocalDateTime start = LocalDateTime.parse("2020-01-01T08:00:00");
|
||||
LocalDateTime end = LocalDateTime.parse("2020-01-01T12:00:00");
|
||||
assertFalse(Duration.between(start, end)
|
||||
.isNegative());
|
||||
assertTrue(Duration.between(end, start)
|
||||
.isNegative());
|
||||
|
||||
LocalDateTime theTime = LocalDateTime.parse("2023-09-09T08:00:00");
|
||||
assertTrue(Duration.between(theTime, theTime)
|
||||
.isZero());
|
||||
assertFalse(Duration.between(theTime, theTime)
|
||||
.isNegative());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test2() {
|
||||
Instant start = Instant.parse("2017-10-03T10:15:30.00Z");
|
||||
|
@ -53,14 +71,14 @@ public class JavaDurationUnitTest {
|
|||
assertEquals(1, fromMinutes.toHours());
|
||||
|
||||
assertEquals(120, duration.plusSeconds(60)
|
||||
.getSeconds());
|
||||
.getSeconds());
|
||||
assertEquals(30, duration.minusSeconds(30)
|
||||
.getSeconds());
|
||||
.getSeconds());
|
||||
|
||||
assertEquals(120, duration.plus(60, ChronoUnit.SECONDS)
|
||||
.getSeconds());
|
||||
.getSeconds());
|
||||
assertEquals(30, duration.minus(30, ChronoUnit.SECONDS)
|
||||
.getSeconds());
|
||||
.getSeconds());
|
||||
|
||||
Duration fromChar1 = Duration.parse("P1DT1H10M10.5S");
|
||||
Duration fromChar2 = Duration.parse("PT10M");
|
||||
|
|
|
@ -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)
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
|
||||
}
|
|
@ -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,96 @@
|
|||
package com.baeldung.mergeandremoveduplicate;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public class MergeArraysAndRemoveDuplicate {
|
||||
|
||||
public static int[] removeDuplicateOnSortedArray(int[] arr) {
|
||||
// Initialize a new array to store unique elements
|
||||
int[] uniqueArray = new int[arr.length];
|
||||
uniqueArray[0] = arr[0];
|
||||
int uniqueCount = 1;
|
||||
|
||||
// Iterate through the sorted array to remove duplicates
|
||||
for (int i = 1; i < arr.length; i++) {
|
||||
if (arr[i] != arr[i - 1]) {
|
||||
uniqueArray[uniqueCount] = arr[i];
|
||||
uniqueCount++;
|
||||
}
|
||||
}
|
||||
int[] truncatedArray = new int[uniqueCount];
|
||||
System.arraycopy(uniqueArray, 0, truncatedArray, 0, uniqueCount);
|
||||
return truncatedArray;
|
||||
}
|
||||
|
||||
public static int[] mergeAndRemoveDuplicatesUsingStream(int[] arr1, int[] arr2) {
|
||||
Stream<Integer> s1 = Arrays.stream(arr1).boxed();
|
||||
Stream<Integer> s2 = Arrays.stream(arr2).boxed();
|
||||
return Stream.concat(s1, s2)
|
||||
.distinct()
|
||||
.mapToInt(Integer::intValue)
|
||||
.toArray();
|
||||
}
|
||||
|
||||
public static int[] mergeAndRemoveDuplicatesUsingSet(int[] arr1, int[] arr2) {
|
||||
int[] mergedArr = mergeArrays(arr1, arr2);
|
||||
Set<Integer> uniqueInts = new HashSet<>();
|
||||
|
||||
for (int el : mergedArr) {
|
||||
uniqueInts.add(el);
|
||||
}
|
||||
|
||||
return getArrayFromSet(uniqueInts);
|
||||
}
|
||||
|
||||
private static int[] getArrayFromSet(Set<Integer> set) {
|
||||
int[] mergedArrWithoutDuplicated = new int[set.size()];
|
||||
int i = 0;
|
||||
for (Integer el: set) {
|
||||
mergedArrWithoutDuplicated[i] = el;
|
||||
i++;
|
||||
}
|
||||
return mergedArrWithoutDuplicated;
|
||||
}
|
||||
|
||||
public static int[] mergeAndRemoveDuplicates(int[] arr1, int[] arr2) {
|
||||
return removeDuplicate(mergeArrays(arr1, arr2));
|
||||
}
|
||||
|
||||
public static int[] mergeAndRemoveDuplicatesOnSortedArray(int[] arr1, int[] arr2) {
|
||||
return removeDuplicateOnSortedArray(mergeArrays(arr1, arr2));
|
||||
}
|
||||
|
||||
private static int[] mergeArrays(int[] arr1, int[] arr2) {
|
||||
int[] mergedArrays = new int[arr1.length + arr2.length];
|
||||
System.arraycopy(arr1, 0, mergedArrays, 0, arr1.length);
|
||||
System.arraycopy(arr2, 0, mergedArrays, arr1.length, arr2.length);
|
||||
|
||||
return mergedArrays;
|
||||
}
|
||||
private static int[] removeDuplicate(int[] arr) {
|
||||
int[] withoutDuplicates = new int[arr.length];
|
||||
int i = 0;
|
||||
|
||||
for(int element : arr) {
|
||||
if(!isElementPresent(withoutDuplicates, element)) {
|
||||
withoutDuplicates[i] = element;
|
||||
i++;
|
||||
}
|
||||
}
|
||||
int[] truncatedArray = new int[i];
|
||||
System.arraycopy(withoutDuplicates, 0, truncatedArray, 0, i);
|
||||
return truncatedArray;
|
||||
}
|
||||
|
||||
private static boolean isElementPresent(int[] arr, int element) {
|
||||
for(int el : arr) {
|
||||
if(el == element) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,74 @@
|
|||
package com.baeldung.mergeandremoveduplicate;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
|
||||
public class MergeArraysAndRemoveDuplicateUnitTest {
|
||||
|
||||
private final Logger logger = LoggerFactory.getLogger(MergeArraysAndRemoveDuplicateUnitTest.class);
|
||||
|
||||
private static String getCommaDelimited(int[] arr) {
|
||||
return Arrays.stream(arr)
|
||||
.mapToObj(Integer::toString)
|
||||
.collect(Collectors.joining(", "));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNoLibraryAndUnSortedArrays_whenArr1andArr2_thenMergeAndRemoveDuplicates() {
|
||||
int[] arr1 = {3, 2, 1, 4, 5, 6, 8, 7, 9};
|
||||
int[] arr2 = {8, 9, 10, 11, 12, 13, 15, 14, 15, 14, 16, 17};
|
||||
int[] expectedArr = {3, 2, 1, 4, 5, 6, 8, 7, 9, 10, 11, 12, 13, 15, 14, 16, 17};
|
||||
|
||||
int[] mergedArr = MergeArraysAndRemoveDuplicate.mergeAndRemoveDuplicates(arr1, arr2);
|
||||
|
||||
//merged array maintains the order of the elements in the arrays
|
||||
assertArrayEquals(expectedArr, mergedArr);
|
||||
|
||||
logger.info(getCommaDelimited(mergedArr));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNoLibraryAndSortedArrays_whenArr1andArr2_thenMergeAndRemoveDuplicates() {
|
||||
int[] arr1 = {1, 2, 3, 4, 5, 5, 6, 7, 7, 8};
|
||||
int[] arr2 = {8, 9, 10, 11, 12, 13, 14, 15, 15, 16, 17};
|
||||
int[] expectedArr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17};
|
||||
|
||||
int[] mergedArr = MergeArraysAndRemoveDuplicate.mergeAndRemoveDuplicatesOnSortedArray(arr1, arr2);
|
||||
|
||||
assertArrayEquals(expectedArr, mergedArr);
|
||||
|
||||
logger.info(getCommaDelimited(mergedArr));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSet_whenArr1andArr2_thenMergeAndRemoveDuplicates() {
|
||||
int[] arr1 = {3, 2, 1, 4, 5, 6, 8, 7, 9};
|
||||
int[] arr2 = {8, 9, 10, 11, 12, 13, 15, 14, 15, 14, 16, 17};
|
||||
int[] expectedArr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17};
|
||||
|
||||
int[] mergedArr = MergeArraysAndRemoveDuplicate.mergeAndRemoveDuplicatesUsingSet(arr1, arr2);
|
||||
|
||||
assertArrayEquals(expectedArr, mergedArr);
|
||||
|
||||
logger.info(getCommaDelimited(mergedArr));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStream_whenArr1andArr2_thenMergeAndRemoveDuplicates() {
|
||||
int[] arr1 = {3, 2, 1, 4, 5, 6, 8, 7, 9};
|
||||
int[] arr2 = {8, 9, 10, 11, 12, 13, 15, 14, 15, 14, 16, 17};
|
||||
int[] expectedArr = {3, 2, 1, 4, 5, 6, 8, 7, 9, 10, 11, 12, 13, 15, 14, 16, 17};
|
||||
|
||||
int[] mergedArr = MergeArraysAndRemoveDuplicate.mergeAndRemoveDuplicatesUsingStream(arr1, arr2);
|
||||
|
||||
assertArrayEquals(expectedArr, mergedArr);
|
||||
|
||||
logger.info(getCommaDelimited(mergedArr));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,2 @@
|
|||
## Relevant Articles
|
||||
- [Find the Middle Element of an Array in Java](https://www.baeldung.com/java-array-middle-item)
|
|
@ -0,0 +1,46 @@
|
|||
<?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-arrays-operations-advanced-2</artifactId>
|
||||
<name>core-java-arrays-operations-advanced-2</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>maven-assembly-plugin</artifactId>
|
||||
<configuration>
|
||||
<descriptorRefs>
|
||||
<descriptorRef>jar-with-dependencies</descriptorRef>
|
||||
</descriptorRefs>
|
||||
</configuration>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>make-assembly</id>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>single</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
</project>
|
|
@ -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)
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
}
|
|
@ -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,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);
|
||||
}
|
||||
}
|
|
@ -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);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,10 @@
|
|||
package com.baeldung.skippingfirstelement;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface TestableSkip {
|
||||
|
||||
void reset();
|
||||
|
||||
List<?> getResult();
|
||||
}
|
|
@ -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,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)
|
|
@ -0,0 +1,32 @@
|
|||
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>core-java-collections-array-list-2</artifactId>
|
||||
<name>core-java-collections-array-list-2</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>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<configuration>
|
||||
<source>${maven-compiler-plugin.source}</source>
|
||||
<target>${maven-compiler-plugin.target}</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<maven-compiler-plugin.source>17</maven-compiler-plugin.source>
|
||||
<maven-compiler-plugin.target>17</maven-compiler-plugin.target>
|
||||
</properties>
|
||||
</project>
|
|
@ -0,0 +1,51 @@
|
|||
package com.baeldung.list.multipleobjecttypes;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.TreeMap;
|
||||
import java.util.function.Predicate;
|
||||
|
||||
public class AlternativeMultipeTypeList {
|
||||
|
||||
public static void main(String[] args) {
|
||||
// List of Parent Class
|
||||
ArrayList<Number> myList = new ArrayList<>();
|
||||
myList.add(1.2);
|
||||
myList.add(2);
|
||||
myList.add(-3.5);
|
||||
|
||||
// List of Interface type
|
||||
ArrayList<Map> diffMapList = new ArrayList<>();
|
||||
diffMapList.add(new HashMap<>());
|
||||
diffMapList.add(new TreeMap<>());
|
||||
diffMapList.add(new LinkedHashMap<>());
|
||||
|
||||
// List of Custom Object
|
||||
ArrayList<CustomObject> objList = new ArrayList<>();
|
||||
objList.add(new CustomObject("String"));
|
||||
objList.add(new CustomObject(2));
|
||||
|
||||
// List via Functional Interface
|
||||
List<Object> dataList = new ArrayList<>();
|
||||
|
||||
Predicate<Object> myPredicate = inputData -> (inputData instanceof String || inputData instanceof Integer);
|
||||
|
||||
UserFunctionalInterface myInterface = (listObj, data) -> {
|
||||
if (myPredicate.test(data))
|
||||
listObj.add(data);
|
||||
else
|
||||
System.out.println("Skipping input as data not allowed for class: " + data.getClass()
|
||||
.getSimpleName());
|
||||
return listObj;
|
||||
};
|
||||
|
||||
myInterface.addToList(dataList, Integer.valueOf(2));
|
||||
myInterface.addToList(dataList, Double.valueOf(3.33));
|
||||
myInterface.addToList(dataList, "String Value");
|
||||
myInterface.printList(dataList);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,22 @@
|
|||
package com.baeldung.list.multipleobjecttypes;
|
||||
|
||||
public class CustomObject {
|
||||
String classData;
|
||||
Integer intData;
|
||||
|
||||
CustomObject(String classData) {
|
||||
this.classData = classData;
|
||||
}
|
||||
|
||||
CustomObject(Integer intData) {
|
||||
this.intData = intData;
|
||||
}
|
||||
|
||||
public String getClassData() {
|
||||
return this.classData;
|
||||
}
|
||||
|
||||
public Integer getIntData() {
|
||||
return this.intData;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,40 @@
|
|||
package com.baeldung.list.multipleobjecttypes;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.time.LocalDate;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
public class MultipleObjectTypeArrayList {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
ArrayList<Object> multiTypeList = new ArrayList<>();
|
||||
|
||||
multiTypeList.add(Integer.valueOf(10));
|
||||
multiTypeList.add(Double.valueOf(11.5));
|
||||
multiTypeList.add("String Data");
|
||||
multiTypeList.add(Arrays.asList(1, 2, 3));
|
||||
multiTypeList.add(new CustomObject("Class Data"));
|
||||
multiTypeList.add(BigInteger.valueOf(123456789));
|
||||
multiTypeList.add(LocalDate.of(2023, 9, 19));
|
||||
|
||||
for (Object dataObj : multiTypeList) {
|
||||
if (dataObj instanceof Integer intData)
|
||||
System.out.println("Integer Data : " + intData);
|
||||
else if (dataObj instanceof Double doubleData)
|
||||
System.out.println("Double Data : " + doubleData);
|
||||
else if (dataObj instanceof String stringData)
|
||||
System.out.println("String Data : " + stringData);
|
||||
else if (dataObj instanceof List<?> intList)
|
||||
System.out.println("List Data : " + intList);
|
||||
else if (dataObj instanceof CustomObject customObj)
|
||||
System.out.println("CustomObject Data : " + customObj.getClassData());
|
||||
else if (dataObj instanceof BigInteger bigIntData)
|
||||
System.out.println("BigInteger Data : " + bigIntData);
|
||||
else if (dataObj instanceof LocalDate localDate)
|
||||
System.out.println("LocalDate Data : " + localDate.toString());
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,18 @@
|
|||
package com.baeldung.list.multipleobjecttypes;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@FunctionalInterface
|
||||
public interface UserFunctionalInterface {
|
||||
|
||||
List<Object> addToList(List<Object> list, Object data);
|
||||
|
||||
default void printList(List<Object> dataList) {
|
||||
for (Object data : dataList) {
|
||||
if (data instanceof String stringData)
|
||||
System.out.println("String Data: " + stringData);
|
||||
if (data instanceof Integer intData)
|
||||
System.out.println("Integer Data: " + intData);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,6 @@
|
|||
## Java Collections Cookbooks and Examples
|
||||
|
||||
This module contains articles about conversions among Collection types in Java.
|
||||
|
||||
### Relevant Articles:
|
||||
- [Converting HashMap Values to an ArrayList in Java](https://www.baeldung.com/java-hashmap-arraylist)
|
|
@ -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>
|
|
@ -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());
|
||||
}
|
||||
|
||||
}
|
|
@ -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>
|
|
@ -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));
|
||||
}
|
||||
}
|
|
@ -53,7 +53,7 @@ public class IdentityHashMapDemonstrator {
|
|||
}
|
||||
}
|
||||
|
||||
private static class Book {
|
||||
static class Book {
|
||||
String title;
|
||||
int year;
|
||||
|
||||
|
|
|
@ -1,8 +1,11 @@
|
|||
package com.baeldung.map.identity;
|
||||
|
||||
import com.baeldung.map.identity.IdentityHashMapDemonstrator.Book;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.IdentityHashMap;
|
||||
import org.junit.jupiter.api.condition.EnabledForJreRange;
|
||||
import org.junit.jupiter.api.condition.JRE;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
|
@ -18,4 +21,44 @@ public class IdentityHashMapDemonstratorUnitTest {
|
|||
assertEquals("Fantasy", identityHashMap.get("genre"));
|
||||
assertEquals("Drama", identityHashMap.get(newGenreKey));
|
||||
}
|
||||
|
||||
@Test
|
||||
@EnabledForJreRange(max = JRE.JAVA_19)
|
||||
public void removeEntryComparingValueByEquality() {
|
||||
Book book = new Book("A Passage to India", 1924);
|
||||
IdentityHashMap<Book, String> identityHashMap = new IdentityHashMap<>(10);
|
||||
identityHashMap.put(book, "A great work of fiction");
|
||||
identityHashMap.remove(book, new String("A great work of fiction"));
|
||||
assertEquals(null, identityHashMap.get(book));
|
||||
}
|
||||
|
||||
@Test
|
||||
@EnabledForJreRange(max = JRE.JAVA_19)
|
||||
public void replaceEntryComparingValueByEquality() {
|
||||
Book book = new Book("A Passage to India", 1924);
|
||||
IdentityHashMap<Book, String> identityHashMap = new IdentityHashMap<>(10);
|
||||
identityHashMap.put(book, "A great work of fiction");
|
||||
identityHashMap.replace(book, new String("A great work of fiction"), "One of the greatest books");
|
||||
assertEquals("One of the greatest books", identityHashMap.get(book));
|
||||
}
|
||||
|
||||
@Test
|
||||
@EnabledForJreRange(min = JRE.JAVA_20)
|
||||
public void dontRemoveEntryComparingValueByEquality() {
|
||||
Book book = new Book("A Passage to India", 1924);
|
||||
IdentityHashMap<Book, String> identityHashMap = new IdentityHashMap<>(10);
|
||||
identityHashMap.put(book, "A great work of fiction");
|
||||
identityHashMap.remove(book, new String("A great work of fiction"));
|
||||
assertEquals("A great work of fiction", identityHashMap.get(book));
|
||||
}
|
||||
|
||||
@Test
|
||||
@EnabledForJreRange(min = JRE.JAVA_20)
|
||||
public void dontReplaceEntryComparingValueByEquality() {
|
||||
Book book = new Book("A Passage to India", 1924);
|
||||
IdentityHashMap<Book, String> identityHashMap = new IdentityHashMap<>(10);
|
||||
identityHashMap.put(book, "A great work of fiction");
|
||||
identityHashMap.replace(book, new String("A great work of fiction"), "One of the greatest books");
|
||||
assertEquals("A great work of fiction", identityHashMap.get(book));
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
}
|
||||
}
|
|
@ -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));
|
||||
}
|
||||
}
|
|
@ -0,0 +1 @@
|
|||
## Relevant Articles
|
|
@ -0,0 +1,78 @@
|
|||
<?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-maps-7</artifactId>
|
||||
<name>core-java-collections-maps-7</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<properties>
|
||||
<spring.version>5.2.5.RELEASE</spring.version>
|
||||
</properties>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
<version>2.12.4</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-core</artifactId>
|
||||
<version>1.36</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.code.gson</groupId>
|
||||
<artifactId>gson</artifactId>
|
||||
<version>2.8.9</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.json</groupId>
|
||||
<artifactId>json</artifactId>
|
||||
<version>20230227</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.13.1</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
<version>5.8.1</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
<version>5.8.1</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.13.1</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
<version>5.8.1</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.13.1</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,60 @@
|
|||
package com.baeldung.map;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public class ConvertHashMapStringToHashMapObjectUsingtoString {
|
||||
public String name;
|
||||
public int age;
|
||||
|
||||
public ConvertHashMapStringToHashMapObjectUsingtoString(String name, int age) {
|
||||
this.name = name;
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public static ConvertHashMapStringToHashMapObjectUsingtoString deserializeCustomObject(String valueString) {
|
||||
if (valueString.startsWith("{") && valueString.endsWith("}")) {
|
||||
valueString = valueString.substring(1, valueString.length() - 1);
|
||||
String[] parts = valueString.split(",");
|
||||
String name = null;
|
||||
int age = -1;
|
||||
for (String part : parts) {
|
||||
String[] keyValue = part.split("=");
|
||||
if (keyValue.length == 2) {
|
||||
String key = keyValue[0].trim();
|
||||
String val = keyValue[1].trim();
|
||||
if (key.equals("name")) {
|
||||
name = val;
|
||||
} else if (key.equals("age")) {
|
||||
age = Integer.parseInt(val);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (name != null && age >= 0) {
|
||||
return new ConvertHashMapStringToHashMapObjectUsingtoString(name, age);
|
||||
}
|
||||
}
|
||||
return new ConvertHashMapStringToHashMapObjectUsingtoString("", -1);
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
String hashMapString = "{key1={name=John, age=30}, key2={name=Alice, age=25}}";
|
||||
String keyValuePairs = hashMapString.replaceAll("[{}\\s]", "");
|
||||
String[] pairs = keyValuePairs.split(",");
|
||||
Map<String, ConvertHashMapStringToHashMapObjectUsingtoString> actualHashMap = new HashMap<>();
|
||||
for (String pair : pairs) {
|
||||
String[] keyValue = pair.split("=");
|
||||
if (keyValue.length == 2) {
|
||||
String key = keyValue[0];
|
||||
ConvertHashMapStringToHashMapObjectUsingtoString value = deserializeCustomObject(keyValue[1]);
|
||||
actualHashMap.put(key, value);
|
||||
}
|
||||
}
|
||||
System.out.println(actualHashMap);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "{name=" + name + ", age=" + age + "}";
|
||||
}
|
||||
}
|
|
@ -0,0 +1,31 @@
|
|||
package com.baeldung.map;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
class ConvertHashMapStringToHashMapObjectUsingtoStringUnitTest {
|
||||
|
||||
@Test
|
||||
void givenValidCustomObject_whenSerializing_thenSerializedStringIsCorrect() {
|
||||
ConvertHashMapStringToHashMapObjectUsingtoString customObject = new ConvertHashMapStringToHashMapObjectUsingtoString("John", 30);
|
||||
String expectedSerializedString = "{name=John, age=30}";
|
||||
assertEquals(expectedSerializedString, customObject.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenValidSerializedString_whenDeserializing_thenCustomObjectIsCorrect() {
|
||||
String serializedString = "{name=Alice, age=25}";
|
||||
ConvertHashMapStringToHashMapObjectUsingtoString customObject = ConvertHashMapStringToHashMapObjectUsingtoString.deserializeCustomObject(serializedString);
|
||||
assertEquals("Alice", customObject.name);
|
||||
assertEquals(25, customObject.age);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenInvalidSerializedString_whenDeserializing_thenDefaultCustomObjectIsCreated() {
|
||||
String invalidSerializedString = "{invalidString}";
|
||||
ConvertHashMapStringToHashMapObjectUsingtoString customObject = ConvertHashMapStringToHashMapObjectUsingtoString.deserializeCustomObject(invalidSerializedString);
|
||||
assertEquals("", customObject.name);
|
||||
assertEquals(-1, customObject.age);
|
||||
}
|
||||
}
|
|
@ -5,4 +5,5 @@
|
|||
- [Sorting a HashSet in Java](https://www.baeldung.com/java-sort-hashset)
|
||||
- [How to Get First Item From a Java Set](https://www.baeldung.com/first-item-set)
|
||||
- [Cartesian Product of Any Number of Sets in Java](https://www.baeldung.com/java-cartesian-product-sets)
|
||||
- [How to Get Index of an Item in Java Set](https://www.baeldung.com/java-set-element-find-index)
|
||||
- More articles: [[<-- prev]](/core-java-modules/core-java-collections-set)
|
||||
|
|
|
@ -5,4 +5,5 @@
|
|||
- [Java Concurrent HashSet Equivalent to ConcurrentHashMap](https://www.baeldung.com/java-concurrent-hashset-concurrenthashmap)
|
||||
- [Reading and Writing With a ConcurrentHashMap](https://www.baeldung.com/concurrenthashmap-reading-and-writing)
|
||||
- [ArrayBlockingQueue vs. LinkedBlockingQueue](https://www.baeldung.com/java-arrayblockingqueue-vs-linkedblockingqueue)
|
||||
- [Difference Between Hashtable and ConcurrentHashMap in Java](https://www.baeldung.com/java-hashtable-vs-concurrenthashmap)
|
||||
- [[<-- Prev]](/core-java-modules/core-java-concurrency-collections)
|
||||
|
|
|
@ -12,10 +12,10 @@ public class EpochTimeToLocalDateTimeConverterUnitTest {
|
|||
@Test
|
||||
public void testConvertEpochTimeToLocalDateTime() {
|
||||
long epochTimeMillis = 1624962431000L; // Example epoch time in milliseconds
|
||||
LocalDateTime expectedDateTime = LocalDateTime.of(2021, 6, 29, 12, 13, 51);
|
||||
LocalDateTime expectedDateTime = LocalDateTime.of(2021, 6, 29, 10, 27, 11);
|
||||
|
||||
Instant instant = Instant.ofEpochMilli(epochTimeMillis);
|
||||
ZoneId zoneId = ZoneId.systemDefault();
|
||||
ZoneId zoneId = ZoneId.of("UTC");
|
||||
LocalDateTime actualDateTime = instant.atZone(zoneId).toLocalDateTime();
|
||||
|
||||
assertEquals(expectedDateTime, actualDateTime);
|
||||
|
|
|
@ -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
|
||||
|
@ -191,4 +194,36 @@ public class DateTimeFormatterUnitTest {
|
|||
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)
|
||||
|
|
|
@ -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");
|
||||
}
|
||||
|
||||
}
|
|
@ -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");
|
||||
}
|
||||
|
||||
}
|
|
@ -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");
|
||||
}
|
||||
|
||||
}
|
|
@ -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");
|
||||
}
|
||||
}
|
|
@ -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;
|
||||
}
|
||||
|
||||
}
|
|
@ -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:
|
||||
- [Get File Extension From MIME Type in Java](https://www.baeldung.com/java-mime-type-file-extension)
|
||||
- [[<-- 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>
|
|
@ -11,11 +11,9 @@ import java.util.Map;
|
|||
import java.util.Set;
|
||||
|
||||
import org.apache.tika.mime.MimeTypeException;
|
||||
|
||||
import com.j256.simplemagic.ContentType;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.j256.simplemagic.ContentInfo;
|
||||
|
||||
public class ExtensionFromMimeTypeUnitTest {
|
||||
private static final String IMAGE_JPEG_MIME_TYPE = "image/jpeg";
|
||||
@Test
|
||||
|
@ -37,15 +35,14 @@ public class ExtensionFromMimeTypeUnitTest {
|
|||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingMimetypesFileTypeMap_thenGetFileExtension() {
|
||||
public void whenUsingSimpleMagic_thenGetFileExtension() {
|
||||
List<String> expectedExtensions = Arrays.asList("jpeg", "jpg", "jpe");
|
||||
ContentInfo contentInfo = new ContentInfo("", IMAGE_JPEG_MIME_TYPE, "", true);
|
||||
String[] detectedExtensions = contentInfo.getFileExtensions();
|
||||
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");
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue