Merge branch 'eugenp:master' into master
This commit is contained in:
@@ -0,0 +1,38 @@
|
||||
---
|
||||
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. The link to the module is the one in the "over on GitHub" standard phrase.
|
||||
|
||||
**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.
|
||||
|
||||
Note that, unfortunately, we can only help with issues that are specifically and directly related to the article - not with your own, custom application.
|
||||
|
||||
StackOverflow is a great place to ask more general questions.
|
||||
|
||||
That's primarily because we get a large number of questions and - while we do try to go through as much as everything and help wherever we can, we can't really get back to all of them.
|
||||
@@ -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,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;
|
||||
}
|
||||
|
||||
}
|
||||
+42
@@ -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;
|
||||
}
|
||||
}
|
||||
+37
@@ -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;
|
||||
}
|
||||
}
|
||||
+39
@@ -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;
|
||||
}
|
||||
}
|
||||
+13
@@ -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.
+53
@@ -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());
|
||||
}
|
||||
|
||||
}
|
||||
+70
@@ -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)
|
||||
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
package com.baeldung.value_based_class;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
import jdk.internal.ValueBased;
|
||||
|
||||
/**
|
||||
* This class is written with the intention that it can serve as an example of
|
||||
* what a Value-based class could be.
|
||||
*/
|
||||
|
||||
@ValueBased
|
||||
public final class Point {
|
||||
private final int x;
|
||||
private final int y;
|
||||
private final int z;
|
||||
|
||||
private static Point ORIGIN = new Point(0, 0, 0);
|
||||
|
||||
private Point(int x, int y, int z) {
|
||||
this.x = x;
|
||||
this.y = y;
|
||||
this.z = z;
|
||||
}
|
||||
|
||||
public static Point valueOfPoint(int x, int y, int z) {
|
||||
// returns a cached instance if it is origin, or a new instance
|
||||
if (isOrigin(x, y, z))
|
||||
return ORIGIN;
|
||||
return new Point(x, y, z);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object other) {
|
||||
if (other == null || getClass() != other.getClass())
|
||||
return false;
|
||||
Point point = (Point) other;
|
||||
return x == point.x && y == point.y && z == point.z;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(x, y, z);
|
||||
}
|
||||
|
||||
private static boolean isOrigin(int x, int y, int z) {
|
||||
return x == 0 && y == 0 && z == 0;
|
||||
}
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
package com.baeldung.value_based_class;
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenValueBasedPoint_whenCreated_thenReturnsObjects() {
|
||||
Point p1 = Point.valueOfPoint(1, 2, 3);
|
||||
Point p2 = Point.valueOfPoint(2, 3, 4);
|
||||
|
||||
Assert.assertNotEquals(p1, p2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenValueBasedPoint_whenCompared_thenReturnEquals() {
|
||||
Point p1 = Point.valueOfPoint(1, 2, 3);
|
||||
Point p2 = Point.valueOfPoint(1, 2, 3);
|
||||
|
||||
Assert.assertEquals(p1, p2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenValueBasedPoint_whenOrigin_thenReturnCachedInstance() {
|
||||
Point p1 = Point.valueOfPoint(0, 0, 0);
|
||||
Point p2 = Point.valueOfPoint(0, 0, 0);
|
||||
Point p3 = Point.valueOfPoint(1, 2, 3);
|
||||
|
||||
// the following should not be assumed for value-based classes
|
||||
|
||||
Assert.assertTrue(p1 == p2);
|
||||
Assert.assertFalse(p1 == p3);
|
||||
}
|
||||
}
|
||||
@@ -1 +1,2 @@
|
||||
## Relevant Articles
|
||||
## Relevant Articles
|
||||
- [Sequenced Collections in Java 21](https://www.baeldung.com/java-21-sequenced-collections)
|
||||
|
||||
@@ -12,23 +12,22 @@
|
||||
<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>-->
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<configuration>
|
||||
<source>21</source>
|
||||
<target>21</target>
|
||||
<compilerArgs>--enable-preview</compilerArgs>
|
||||
</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>
|
||||
</project>
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
package com.baeldung.stringtemplates;
|
||||
|
||||
import java.text.MessageFormat;
|
||||
|
||||
public class StringCompositionTechniques {
|
||||
String composeUsingPlus(String feelsLike, String temperature, String unit) {
|
||||
return "Today's weather is " + feelsLike + ", with a temperature of " + temperature + " degrees " + unit;
|
||||
}
|
||||
|
||||
String composeUsingStringBuffer(String feelsLike, String temperature, String unit) {
|
||||
return new StringBuffer().append("Today's weather is ")
|
||||
.append(feelsLike)
|
||||
.append(", with a temperature of ")
|
||||
.append(temperature)
|
||||
.append(" degrees ")
|
||||
.append(unit)
|
||||
.toString();
|
||||
}
|
||||
|
||||
String composeUsingStringBuilder(String feelsLike, String temperature, String unit) {
|
||||
return new StringBuilder().append("Today's weather is ")
|
||||
.append(feelsLike)
|
||||
.append(", with a temperature of ")
|
||||
.append(temperature)
|
||||
.append(" degrees ")
|
||||
.append(unit)
|
||||
.toString();
|
||||
}
|
||||
|
||||
String composeUsingFormatters(String feelsLike, String temperature, String unit) {
|
||||
return String.format("Today's weather is %s, with a temperature of %s degrees %s", feelsLike, temperature, unit);
|
||||
}
|
||||
|
||||
String composeUsingMessageFormatter(String feelsLike, String temperature, String unit) {
|
||||
return MessageFormat.format("Today''s weather is {0}, with a temperature of {1} degrees {2}", feelsLike, temperature, unit);
|
||||
}
|
||||
}
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
package com.baeldung.stringtemplates;
|
||||
|
||||
import static java.lang.StringTemplate.RAW;
|
||||
import static java.util.FormatProcessor.FMT;
|
||||
|
||||
public class StringTemplateExamples {
|
||||
String interpolationUsingSTRProcessor(String feelsLike, String temperature, String unit) {
|
||||
return STR
|
||||
. "Today's weather is \{ feelsLike }, with a temperature of \{ temperature } degrees \{ unit }" ;
|
||||
}
|
||||
|
||||
String interpolationOfJSONBlock(String feelsLike, String temperature, String unit) {
|
||||
return STR
|
||||
. """
|
||||
{
|
||||
"feelsLike": "\{ feelsLike }",
|
||||
"temperature": "\{ temperature }",
|
||||
"unit": "\{ unit }"
|
||||
}
|
||||
""" ;
|
||||
}
|
||||
|
||||
String interpolationWithExpressions() {
|
||||
return STR
|
||||
. "Today's weather is \{ getFeelsLike() }, with a temperature of \{ getTemperature() } degrees \{ getUnit() }" ;
|
||||
}
|
||||
|
||||
String interpolationWithTemplates() {
|
||||
StringTemplate str = RAW
|
||||
. "Today's weather is \{ getFeelsLike() }, with a temperature of \{ getTemperature() } degrees \{ getUnit() }" ;
|
||||
return STR.process(str);
|
||||
}
|
||||
|
||||
String interpolationOfJSONBlockWithFMT(String feelsLike, float temperature, String unit) {
|
||||
return FMT
|
||||
. """
|
||||
{
|
||||
"feelsLike": "%1s\{ feelsLike }",
|
||||
"temperature": "%2.2f\{ temperature }",
|
||||
"unit": "%1s\{ unit }"
|
||||
}
|
||||
""" ;
|
||||
}
|
||||
|
||||
private String getFeelsLike() {
|
||||
return "pleasant";
|
||||
}
|
||||
|
||||
private String getTemperature() {
|
||||
return "25";
|
||||
}
|
||||
|
||||
private String getUnit() {
|
||||
return "Celsius";
|
||||
}
|
||||
}
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
package com.baeldung.stringtemplates;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class StringTemplatesUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenStringConcat_thenReturnComposedString() {
|
||||
StringCompositionTechniques stringCompositionTechniques = new StringCompositionTechniques();
|
||||
Assert.assertEquals("Today's weather is pleasant, with a temperature of 25 degrees Celsius", stringCompositionTechniques.composeUsingPlus("pleasant", "25", "Celsius"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenStringBuffer_thenReturnComposedString() {
|
||||
StringCompositionTechniques stringCompositionTechniques = new StringCompositionTechniques();
|
||||
Assert.assertEquals("Today's weather is pleasant, with a temperature of 25 degrees Celsius", stringCompositionTechniques.composeUsingStringBuffer("pleasant", "25", "Celsius"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenStringBuilder_thenReturnComposedString() {
|
||||
StringCompositionTechniques stringCompositionTechniques = new StringCompositionTechniques();
|
||||
Assert.assertEquals("Today's weather is pleasant, with a temperature of 25 degrees Celsius", stringCompositionTechniques.composeUsingStringBuilder("pleasant", "25", "Celsius"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenStringFormatter_thenReturnComposedFormattedString() {
|
||||
StringCompositionTechniques stringCompositionTechniques = new StringCompositionTechniques();
|
||||
Assert.assertEquals("Today's weather is pleasant, with a temperature of 25 degrees Celsius", stringCompositionTechniques.composeUsingFormatters("pleasant", "25", "Celsius"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenMessageFormatter_thenReturnComposedFormattedString() {
|
||||
StringCompositionTechniques stringCompositionTechniques = new StringCompositionTechniques();
|
||||
Assert.assertEquals("Today's weather is pleasant, with a temperature of 25 degrees Celsius", stringCompositionTechniques.composeUsingMessageFormatter("pleasant", "25", "Celsius"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingStringTemplateSTR_thenReturnInterpolatedString() {
|
||||
StringTemplateExamples templateExamples = new StringTemplateExamples();
|
||||
Assert.assertEquals("Today's weather is pleasant, with a temperature of 25 degrees Celsius", templateExamples.interpolationUsingSTRProcessor("pleasant", "25", "Celsius"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingMultilineStringTemplateSTR_thenReturnInterpolatedString() {
|
||||
StringTemplateExamples templateExamples = new StringTemplateExamples();
|
||||
Assert.assertEquals("{\n" + " \"feelsLike\": \"pleasant\",\n" + " \"temperature\": \"25\",\n" + " \"unit\": \"Celsius\"\n" + "}\n", templateExamples.interpolationOfJSONBlock("pleasant", "25", "Celsius"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingExpressionSTR_thenReturnInterpolatedString() {
|
||||
StringTemplateExamples templateExamples = new StringTemplateExamples();
|
||||
Assert.assertEquals("Today's weather is pleasant, with a temperature of 25 degrees Celsius", templateExamples.interpolationWithExpressions());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingExpressionRAW_thenReturnInterpolatedString() {
|
||||
StringTemplateExamples templateExamples = new StringTemplateExamples();
|
||||
Assert.assertEquals("Today's weather is pleasant, with a temperature of 25 degrees Celsius", templateExamples.interpolationWithTemplates());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingExpressionFMT_thenReturnInterpolatedString() {
|
||||
StringTemplateExamples templateExamples = new StringTemplateExamples();
|
||||
Assert.assertEquals("{\n" + " \"feelsLike\": \"pleasant\",\n" + " \"temperature\": \"25.86\",\n" + " \"unit\": \"Celsius\"\n" + "}\n", templateExamples.interpolationOfJSONBlockWithFMT("pleasant", 25.8636F, "Celsius"));
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
package com.baeldung.stringtime;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.time.LocalTime;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class AddMinuteStringTimeUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenTimeStringUsingSimpleDateFormat_whenIncrementedWith10Minutes_thenResultShouldBeCorrect() throws ParseException {
|
||||
String timeString = "23:45";
|
||||
SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm");
|
||||
Date date = timeFormat.parse(timeString);
|
||||
|
||||
Calendar cal = Calendar.getInstance();
|
||||
cal.setTime(date);
|
||||
cal.add(Calendar.MINUTE, 10);
|
||||
String result = timeFormat.format(cal.getTime());
|
||||
assertEquals("23:55", result);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTimeStringUsingLocalTime_whenIncrementedWith10Minutes_thenResultShouldBeCorrect() {
|
||||
String timeString = "23:45";
|
||||
LocalTime time = LocalTime.parse(timeString);
|
||||
LocalTime newTime = time.plusMinutes(10);
|
||||
String result = newTime.toString();
|
||||
assertEquals("23:55", result);
|
||||
}
|
||||
|
||||
}
|
||||
+24
-6
@@ -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,17 +71,17 @@ 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");
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
+96
@@ -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;
|
||||
}
|
||||
}
|
||||
+74
@@ -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,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>
|
||||
+1
-1
@@ -62,4 +62,4 @@ public class MiddleOfArray {
|
||||
return array[mid];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -86,4 +86,4 @@ public class MiddleOfArrayUnitTest {
|
||||
MiddleOfArray middleOfArray = new MiddleOfArray();
|
||||
Assert.assertEquals(expectMedian, middleOfArray.medianOfArray(array, 0, 100));
|
||||
}
|
||||
}
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package com.baeldung.collectionsvsarrays;
|
||||
|
||||
import com.baeldung.collectionsvsarrays.sorting.Quicksort;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
|
||||
public class NonStableSortExample {
|
||||
|
||||
|
||||
|
||||
public static void main(String[] args) {
|
||||
List<Task> tasks = Tasks.supplier.get();
|
||||
Quicksort.sort(tasks, Comparator.comparingInt(Task::getPriority));
|
||||
System.out.println("After sorting by priority:");
|
||||
for (Task task : tasks) {
|
||||
System.out.println(task);
|
||||
}
|
||||
Quicksort.sort(tasks, Comparator.comparing(Task::getDueDate));
|
||||
System.out.println("\nAfter sorting by due date:");
|
||||
for (Task task : tasks) {
|
||||
System.out.println(task);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
package com.baeldung.collectionsvsarrays;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.Collectors;
|
||||
import org.openjdk.jmh.annotations.Benchmark;
|
||||
import org.openjdk.jmh.annotations.BenchmarkMode;
|
||||
import org.openjdk.jmh.annotations.Fork;
|
||||
import org.openjdk.jmh.annotations.Measurement;
|
||||
import org.openjdk.jmh.annotations.Mode;
|
||||
import org.openjdk.jmh.annotations.Scope;
|
||||
import org.openjdk.jmh.annotations.State;
|
||||
import org.openjdk.jmh.annotations.Warmup;
|
||||
import org.openjdk.jmh.infra.Blackhole;
|
||||
|
||||
@Measurement(iterations = 2, time = 10, timeUnit = TimeUnit.MINUTES)
|
||||
@Warmup(iterations = 5, time = 10)
|
||||
@Fork(value = 2)
|
||||
public class ObjectOverheadBenchmark {
|
||||
|
||||
private static final ThreadLocalRandom RANDOM = ThreadLocalRandom.current();
|
||||
|
||||
@State(Scope.Benchmark)
|
||||
public static class Input {
|
||||
public Supplier<List<Integer>> randomNumbers = () -> RANDOM.ints().limit(10000).boxed().collect(Collectors.toList());
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.Throughput)
|
||||
public void sortingPrimitiveArray(Input input, Blackhole blackhole) {
|
||||
final int[] array = input.randomNumbers.get().stream().mapToInt(Integer::intValue).toArray();
|
||||
Arrays.sort(array);
|
||||
final List<Integer> result = Arrays.stream(array).boxed().collect(Collectors.toList());
|
||||
blackhole.consume(result);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.Throughput)
|
||||
public void sortingObjectArray(Input input, Blackhole blackhole) {
|
||||
final Integer[] array = input.randomNumbers.get().toArray(new Integer[0]);
|
||||
Arrays.sort(array);
|
||||
blackhole.consume(array);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.Throughput)
|
||||
public void sortingObjects(Input input, Blackhole blackhole) {
|
||||
final List<Integer> list = input.randomNumbers.get();
|
||||
Collections.sort(list);
|
||||
blackhole.consume(list);
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user