Merge remote-tracking branch 'upstream/master'

This commit is contained in:
Tarun Jain 2020-08-22 23:31:14 +05:30
commit 56fe1e809a
1640 changed files with 11417 additions and 3055 deletions

1
.gitignore vendored
View File

@ -85,5 +85,6 @@ transaction.log
*-shell.log
apache-cxf/cxf-aegis/baeldung.xml
testing-modules/report-*.json
libraries-2/*.db

View File

@ -7,4 +7,6 @@
- [Efficiently Merge Sorted Java Sequences](https://www.baeldung.com/java-merge-sorted-sequences)
- [Introduction to Greedy Algorithms with Java](https://www.baeldung.com/java-greedy-algorithms)
- [The Caesar Cipher in Java](https://www.baeldung.com/java-caesar-cipher)
- [Implementing a 2048 Solver in Java](https://www.baeldung.com/2048-java-solver)
- [Finding Top K Elements in an Array](https://www.baeldung.com/java-array-top-elements)
- More articles: [[<-- prev]](/../algorithms-miscellaneous-5)

View File

@ -3,6 +3,7 @@
This module contains articles about searching algorithms.
### Relevant articles:
- [Binary Search Algorithm in Java](https://www.baeldung.com/java-binary-search)
- [Depth First Search in Java](https://www.baeldung.com/java-depth-first-search)
- [Interpolation Search in Java](https://www.baeldung.com/java-interpolation-search)
@ -11,3 +12,4 @@ This module contains articles about searching algorithms.
- [Monte Carlo Tree Search for Tic-Tac-Toe Game](https://www.baeldung.com/java-monte-carlo-tree-search)
- [Range Search Algorithm in Java](https://www.baeldung.com/java-range-search)
- [Fast Pattern Matching of Strings Using Suffix Tree](https://www.baeldung.com/java-pattern-matching-suffix-tree)
- [Find the Kth Smallest Element in Two Sorted Arrays](https://www.baeldung.com/java-kth-smallest-element-in-sorted-arrays)

View File

@ -0,0 +1,126 @@
package com.baeldung.algorithms.kthsmallest;
import java.util.Arrays;
import java.util.NoSuchElementException;
import static java.lang.Math.max;
import static java.lang.Math.min;
public class KthSmallest {
public static int findKthSmallestElement(int k, int[] list1, int[] list2) throws NoSuchElementException, IllegalArgumentException {
checkInput(k, list1, list2);
// we are looking for the minimum value
if(k == 1) {
return min(list1[0], list2[0]);
}
// we are looking for the maximum value
if(list1.length + list2.length == k) {
return max(list1[list1.length-1], list2[list2.length-1]);
}
// swap lists if needed to make sure we take at least one element from list1
if(k <= list2.length && list2[k-1] < list1[0]) {
int[] list1_ = list1;
list1 = list2;
list2 = list1_;
}
// correct left boundary if k is bigger than the size of list2
int left = k < list2.length ? 0 : k - list2.length - 1;
// the inital right boundary cannot exceed the list1
int right = min(k-1, list1.length - 1);
int nElementsList1, nElementsList2;
// binary search
do {
nElementsList1 = ((left + right) / 2) + 1;
nElementsList2 = k - nElementsList1;
if(nElementsList2 > 0) {
if (list1[nElementsList1 - 1] > list2[nElementsList2 - 1]) {
right = nElementsList1 - 2;
} else {
left = nElementsList1;
}
}
} while(!kthSmallesElementFound(list1, list2, nElementsList1, nElementsList2));
return nElementsList2 == 0 ? list1[nElementsList1-1] : max(list1[nElementsList1-1], list2[nElementsList2-1]);
}
private static boolean kthSmallesElementFound(int[] list1, int[] list2, int nElementsList1, int nElementsList2) {
// we do not take any element from the second list
if(nElementsList2 < 1) {
return true;
}
if(list1[nElementsList1-1] == list2[nElementsList2-1]) {
return true;
}
if(nElementsList1 == list1.length) {
return list1[nElementsList1-1] <= list2[nElementsList2];
}
if(nElementsList2 == list2.length) {
return list2[nElementsList2-1] <= list1[nElementsList1];
}
return list1[nElementsList1-1] <= list2[nElementsList2] && list2[nElementsList2-1] <= list1[nElementsList1];
}
private static void checkInput(int k, int[] list1, int[] list2) throws NoSuchElementException, IllegalArgumentException {
if(list1 == null || list2 == null || k < 1) {
throw new IllegalArgumentException();
}
if(list1.length == 0 || list2.length == 0) {
throw new IllegalArgumentException();
}
if(k > list1.length + list2.length) {
throw new NoSuchElementException();
}
}
public static int getKthElementSorted(int[] list1, int[] list2, int k) {
int length1 = list1.length, length2 = list2.length;
int[] combinedArray = new int[length1 + length2];
System.arraycopy(list1, 0, combinedArray, 0, list1.length);
System.arraycopy(list2, 0, combinedArray, list1.length, list2.length);
Arrays.sort(combinedArray);
return combinedArray[k-1];
}
public static int getKthElementMerge(int[] list1, int[] list2, int k) {
int i1 = 0, i2 = 0;
while(i1 < list1.length && i2 < list2.length && (i1 + i2) < k) {
if(list1[i1] < list2[i2]) {
i1++;
} else {
i2++;
}
}
if((i1 + i2) < k) {
return i1 < list1.length ? list1[k - i2 - 1] : list2[k - i1 - 1];
} else if(i1 > 0 && i2 > 0) {
return Math.max(list1[i1-1], list2[i2-1]);
} else {
return i1 == 0 ? list2[i2-1] : list1[i1-1];
}
}
}

View File

@ -0,0 +1,288 @@
package com.baeldung.algorithms.kthsmallest;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.Executable;
import java.util.*;
import static com.baeldung.algorithms.kthsmallest.KthSmallest.*;
import static org.junit.jupiter.api.Assertions.*;
public class KthSmallestUnitTest {
@Nested
class Exceptions {
@Test
public void when_at_least_one_list_is_null_then_an_exception_is_thrown() {
Executable executable1 = () -> findKthSmallestElement(1, null, null);
Executable executable2 = () -> findKthSmallestElement(1, new int[]{2}, null);
Executable executable3 = () -> findKthSmallestElement(1, null, new int[]{2});
assertThrows(IllegalArgumentException.class, executable1);
assertThrows(IllegalArgumentException.class, executable2);
assertThrows(IllegalArgumentException.class, executable3);
}
@Test
public void when_at_least_one_list_is_empty_then_an_exception_is_thrown() {
Executable executable1 = () -> findKthSmallestElement(1, new int[]{}, new int[]{2});
Executable executable2 = () -> findKthSmallestElement(1, new int[]{2}, new int[]{});
Executable executable3 = () -> findKthSmallestElement(1, new int[]{}, new int[]{});
assertThrows(IllegalArgumentException.class, executable1);
assertThrows(IllegalArgumentException.class, executable2);
assertThrows(IllegalArgumentException.class, executable3);
}
@Test
public void when_k_is_smaller_than_0_then_an_exception_is_thrown() {
Executable executable1 = () -> findKthSmallestElement(-1, new int[]{2}, new int[]{2});
assertThrows(IllegalArgumentException.class, executable1);
}
@Test
public void when_k_is_smaller_than_1_then_an_exception_is_thrown() {
Executable executable1 = () -> findKthSmallestElement(0, new int[]{2}, new int[]{2});
assertThrows(IllegalArgumentException.class, executable1);
}
@Test
public void when_k_bigger_then_the_two_lists_then_an_exception_is_thrown() {
Executable executable1 = () -> findKthSmallestElement(6, new int[]{1, 5, 6}, new int[]{2, 5});
assertThrows(NoSuchElementException.class, executable1);
}
}
@Nested
class K_is_smaller_than_the_size_of_list1_and_the_size_of_list2 {
@Test
public void when_k_is_1_then_the_smallest_element_is_returned_from_list1() {
int result = findKthSmallestElement(1, new int[]{2, 7}, new int[]{3, 5});
assertEquals(2, result);
}
@Test
public void when_k_is_1_then_the_smallest_element_is_returned_list2() {
int result = findKthSmallestElement(1, new int[]{3, 5}, new int[]{2, 7});
assertEquals(2, result);
}
@Test
public void when_kth_element_is_smallest_element_and_occurs_in_both_lists() {
int[] list1 = new int[]{1, 2, 3};
int[] list2 = new int[]{1, 2, 3};
int result = findKthSmallestElement(1, list1, list2);
assertEquals(1, result);
}
@Test
public void when_kth_element_is_smallest_element_and_occurs_in_both_lists2() {
int[] list1 = new int[]{1, 2, 3};
int[] list2 = new int[]{1, 2, 3};
int result = findKthSmallestElement(2, list1, list2);
assertEquals(1, result);
}
@Test
public void when_kth_element_is_largest_element_and_occurs_in_both_lists_1() {
int[] list1 = new int[]{1, 2, 3};
int[] list2 = new int[]{1, 2, 3};
int result = findKthSmallestElement(5, list1, list2);
assertEquals(3, result);
}
@Test
public void when_kth_element_is_largest_element_and_occurs_in_both_lists_2() {
int[] list1 = new int[]{1, 2, 3};
int[] list2 = new int[]{1, 2, 3};
int result = findKthSmallestElement(6, list1, list2);
assertEquals(3, result);
}
@Test
public void when_kth_element_and_occurs_in_both_lists() {
int[] list1 = new int[]{1, 2, 3};
int[] list2 = new int[]{0, 2, 3};
int result = findKthSmallestElement(3, list1, list2);
assertEquals(2, result);
}
@Test
public void and_kth_element_is_in_first_list() {
int[] list1 = new int[]{1,2,3,4};
int[] list2 = new int[]{1,3,4,5};
int result = findKthSmallestElement(3, list1, list2);
assertEquals(2, result);
}
@Test
public void and_kth_is_in_second_list() {
int[] list1 = new int[]{1,3,4,4};
int[] list2 = new int[]{1,2,4,5};
int result = findKthSmallestElement(3, list1, list2);
assertEquals(2, result);
}
@Test
public void and_elements_in_first_list_are_all_smaller_than_second_list() {
int[] list1 = new int[]{1,3,7,9};
int[] list2 = new int[]{11,12,14,15};
int result = findKthSmallestElement(3, list1, list2);
assertEquals(7, result);
}
@Test
public void and_elements_in_first_list_are_all_smaller_than_second_list2() {
int[] list1 = new int[]{1,3,7,9};
int[] list2 = new int[]{11,12,14,15};
int result = findKthSmallestElement(4, list1, list2);
assertEquals(9, result);
}
@Test
public void and_only_elements_from_second_list_are_part_of_result() {
int[] list1 = new int[]{11,12,14,15};
int[] list2 = new int[]{1,3,7,9};
int result = findKthSmallestElement(3, list1, list2);
assertEquals(7, result);
}
@Test
public void and_only_elements_from_second_list_are_part_of_result2() {
int[] list1 = new int[]{11,12,14,15};
int[] list2 = new int[]{1,3,7,9};
int result = findKthSmallestElement(4, list1, list2);
assertEquals(9, result);
}
}
@Nested
class K_is_bigger_than_the_size_of_at_least_one_of_the_lists {
@Test
public void k_is_smaller_than_list1_and_bigger_than_list2() {
int[] list1 = new int[]{1, 2, 3, 4, 7, 9};
int[] list2 = new int[]{1, 2, 3};
int result = findKthSmallestElement(5, list1, list2);
assertEquals(3, result);
}
@Test
public void k_is_bigger_than_list1_and_smaller_than_list2() {
int[] list1 = new int[]{1, 2, 3};
int[] list2 = new int[]{1, 2, 3, 4, 7, 9};
int result = findKthSmallestElement(5, list1, list2);
assertEquals(3, result);
}
@Test
public void when_k_is_bigger_than_the_size_of_both_lists_and_elements_in_second_list_are_all_smaller_than_first_list() {
int[] list1 = new int[]{9, 11, 13, 55};
int[] list2 = new int[]{1, 2, 3, 7};
int result = findKthSmallestElement(6, list1, list2);
assertEquals(11, result);
}
@Test
public void when_k_is_bigger_than_the_size_of_both_lists_and_elements_in_second_list_are_all_bigger_than_first_list() {
int[] list1 = new int[]{1, 2, 3, 7};
int[] list2 = new int[]{9, 11, 13, 55};
int result = findKthSmallestElement(6, list1, list2);
assertEquals(11, result);
}
@Test
public void when_k_is_bigger_than_the_size_of_both_lists() {
int[] list1 = new int[]{3, 7, 9, 11, 55};
int[] list2 = new int[]{1, 2, 3, 7, 13};
int result = findKthSmallestElement(7, list1, list2);
assertEquals(9, result);
}
@Test
public void when_k_is_bigger_than_the_size_of_both_lists_and_list1_has_more_elements_than_list2() {
int[] list1 = new int[]{3, 7, 9, 11, 55, 77, 100, 200};
int[] list2 = new int[]{1, 2, 3, 7, 13};
int result = findKthSmallestElement(11, list1, list2);
assertEquals(77, result);
}
@Test
public void max_test() {
int[] list1 = new int[]{100, 200};
int[] list2 = new int[]{1, 2, 3};
int result = findKthSmallestElement(4, list1, list2);
assertEquals(100, result);
}
@Test
public void max_test2() {
int[] list1 = new int[]{100, 200};
int[] list2 = new int[]{1, 2, 3};
int result = findKthSmallestElement(5, list1, list2);
assertEquals(200, result);
}
@Test
public void when_k_is_smaller_than_the_size_of_both_lists_and_kth_element_in_list2() {
int[] list1 = new int[]{1, 2, 5};
int[] list2 = new int[]{1, 3, 4, 7};
int result = findKthSmallestElement(4, list1, list2);
assertEquals(3, result);
}
@Test
public void when_k_is_smaller_than_the_size_of_both_lists_and_kth_element_is_smallest_in_list2() {
int[] list1 = new int[]{1, 2, 5};
int[] list2 = new int[]{3, 4, 7};
int result = findKthSmallestElement(3, list1, list2);
assertEquals(3, result);
}
@Test
public void when_k_is_smaller_than_the_size_of_both_lists_and_kth_element_is_smallest_in_list23() {
int[] list1 = new int[]{3, 11, 27, 53, 90};
int[] list2 = new int[]{4, 20, 21, 100};
int result = findKthSmallestElement(5, list1, list2);
assertEquals(21, result);
}
}
// @Test
// public void randomTests() {
// IntStream.range(1, 100000).forEach(i -> random());
// }
private void random() {
Random random = new Random();
int length1 = (Math.abs(random.nextInt())) % 1000 + 1;
int length2 = (Math.abs(random.nextInt())) % 1000 + 1;
int[] list1 = sortedRandomIntArrayOfLength(length1);
int[] list2 = sortedRandomIntArrayOfLength(length2);
int k = (Math.abs(random.nextInt()) % (length1 + length2)) + 1 ;
int result = findKthSmallestElement(k, list1, list2);
int result2 = getKthElementSorted(list1, list2, k);
int result3 = getKthElementMerge(list1, list2, k);
assertEquals(result2, result);
assertEquals(result2, result3);
}
private int[] sortedRandomIntArrayOfLength(int length) {
int[] intArray = new Random().ints(length).toArray();
Arrays.sort(intArray);
return intArray;
}
}

View File

@ -7,4 +7,3 @@ This module contains articles about Apache CXF
- [Apache CXF Support for RESTful Web Services](https://www.baeldung.com/apache-cxf-rest-api)
- [A Guide to Apache CXF with Spring](https://www.baeldung.com/apache-cxf-with-spring)
- [Introduction to Apache CXF](https://www.baeldung.com/introduction-to-apache-cxf)
- [Server-Sent Events (SSE) In JAX-RS](https://www.baeldung.com/java-ee-jax-rs-sse)

View File

@ -0,0 +1,3 @@
### Relevant Articles:
- [Server-Sent Events (SSE) In JAX-RS](https://www.baeldung.com/java-ee-jax-rs-sse)

View File

@ -3,9 +3,11 @@
This module contains articles about Apache POI
### Relevant Articles:
- [Microsoft Word Processing in Java with Apache POI](https://www.baeldung.com/java-microsoft-word-with-apache-poi)
- [Working with Microsoft Excel in Java](https://www.baeldung.com/java-microsoft-excel)
- [Creating a MS PowerPoint Presentation in Java](https://www.baeldung.com/apache-poi-slideshow)
- [Merge Cells in Excel Using Apache POI](https://www.baeldung.com/java-apache-poi-merge-cells)
- [Get String Value of Excel Cell with Apache POI](https://www.baeldung.com/java-apache-poi-cell-string-value)
- [Read Excel Cell Value Rather Than Formula With Apache POI](https://www.baeldung.com/apache-poi-read-cell-value-formula)
- [Setting Formulas in Excel with Apache POI](https://www.baeldung.com/java-apache-poi-set-formulas)

View File

@ -0,0 +1,26 @@
package com.baeldung.poi.excel.setformula;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFFormulaEvaluator;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class ExcelFormula {
public double setFormula(String fileLocation, XSSFWorkbook wb, String formula) throws IOException {
XSSFSheet sheet = wb.getSheetAt(0);
int lastCellNum = sheet.getRow(0).getLastCellNum();
XSSFCell formulaCell = sheet.getRow(0).createCell(lastCellNum);
formulaCell.setCellFormula(formula);
XSSFFormulaEvaluator formulaEvaluator = wb.getCreationHelper().createFormulaEvaluator();
formulaEvaluator.evaluateFormulaCell(formulaCell);
FileOutputStream fileOut = new FileOutputStream(new File(fileLocation));
wb.write(fileOut);
wb.close();
fileOut.close();
return formulaCell.getNumericCellValue();
}
}

View File

@ -0,0 +1,51 @@
package com.baeldung.poi.excel.setformula;
import org.apache.poi.ss.util.CellReference;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.Assert;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Paths;
class ExcelFormulaUnitTest {
private static String FILE_NAME = "com/baeldung/poi/excel/setformula/SetFormulaTest.xlsx";
private String fileLocation;
private ExcelFormula excelFormula;
@BeforeEach
public void setup() throws URISyntaxException {
fileLocation = Paths.get(ClassLoader.getSystemResource(FILE_NAME).toURI()).toString();
excelFormula = new ExcelFormula();
}
@Test
void givenExcelData_whenSetFormula_thenSuccess() throws IOException {
FileInputStream inputStream = new FileInputStream(new File(fileLocation));
XSSFWorkbook wb = new XSSFWorkbook(inputStream);
XSSFSheet sheet = wb.getSheetAt(0);
double resultColumnA = 0;
double resultColumnB = 0;
for (int row = 0; row <= sheet.getLastRowNum(); row++) {
resultColumnA += sheet.getRow(row).getCell(0).getNumericCellValue();
resultColumnB += sheet.getRow(row).getCell(1).getNumericCellValue();
}
String colNameA = CellReference.convertNumToColString(0);
String colNameB = CellReference.convertNumToColString(1);
String startCellA = colNameA + 1;
String stopCellA = colNameA + (sheet.getLastRowNum() + 1);
String sumFormulaForColumnA = String.format("SUM(%s:%s)", startCellA, stopCellA);
String startCellB = colNameB + 1;
String stopCellB = colNameB + (sheet.getLastRowNum() + 1);
String sumFormulaForColumnB = String.format("SUM(%s:%s)", startCellB, stopCellB);
double resultValue = excelFormula.setFormula(fileLocation, wb, sumFormulaForColumnA + "-" + sumFormulaForColumnB);
Assert.assertEquals(resultColumnA - resultColumnB, resultValue, 0d);
}
}

View File

@ -6,4 +6,4 @@ This module contains articles about Apache Shiro
- [Introduction to Apache Shiro](https://www.baeldung.com/apache-shiro)
- [Permissions-Based Access Control with Apache Shiro](https://www.baeldung.com/apache-shiro-access-control)
- [Spring Security vs Apache Shiro](https://www.baeldung.com/spring-security-vs-apache-shiro)

View File

@ -13,4 +13,5 @@ This module contains articles about core Groovy concepts
- [Converting a String to a Date in Groovy](https://www.baeldung.com/groovy-string-to-date)
- [Guide to I/O in Groovy](https://www.baeldung.com/groovy-io)
- [Convert String to Integer in Groovy](https://www.baeldung.com/groovy-convert-string-to-integer)
- [Groovy Variable Scope](https://www.baeldung.com/groovy/variable-scope)
- [[More -->]](/core-groovy-2)

View File

@ -9,3 +9,4 @@ This module contains articles about Java 10 core features
- [Copy a List to Another List in Java](http://www.baeldung.com/java-copy-list-to-another)
- [Deep Dive Into the New Java JIT Compiler Graal](https://www.baeldung.com/graal-java-jit-compiler)
- [Copying Sets in Java](https://www.baeldung.com/java-copy-sets)
- [Converting between a List and a Set in Java](https://www.baeldung.com/convert-list-to-set-and-set-to-list)

View File

@ -1,22 +1,29 @@
<?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">
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-10</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-10</name>
<packaging>jar</packaging>
<url>http://maven.apache.org</url>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../../</relativePath>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>${commons-collections4.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
@ -34,6 +41,7 @@
<properties>
<maven.compiler.source.version>10</maven.compiler.source.version>
<maven.compiler.target.version>10</maven.compiler.target.version>
<commons-collections4.version>4.1</commons-collections4.version>
</properties>
</project>

View File

@ -0,0 +1,68 @@
package com.baeldung.java10.collections.conversion;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.apache.commons.collections4.CollectionUtils;
import org.junit.Test;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class ListSetConversionUnitTest {
// Set -> List; List -> Set
@Test
public final void givenUsingCoreJava_whenSetConvertedToList_thenCorrect() {
final Set<Integer> sourceSet = Sets.newHashSet(0, 1, 2, 3, 4, 5);
final List<Integer> targetList = new ArrayList<>(sourceSet);
}
@Test
public final void givenUsingCoreJava_whenListConvertedToSet_thenCorrect() {
final List<Integer> sourceList = Lists.newArrayList(0, 1, 2, 3, 4, 5);
final Set<Integer> targetSet = new HashSet<>(sourceList);
}
@Test
public void givenUsingJava10_whenSetConvertedToList_thenCorrect() {
final Set<Integer> sourceSet = Sets.newHashSet(0, 1, 2, 3, 4, 5);
final List<Integer> targetList = List.copyOf(sourceSet);
}
@Test
public void givenUsingJava10_whenListConvertedToSet_thenCorrect() {
final List<Integer> sourceList = Lists.newArrayList(0, 1, 2, 3, 4, 5);
final Set<Integer> targetSet = Set.copyOf(sourceList);
}
@Test
public final void givenUsingGuava_whenSetConvertedToList_thenCorrect() {
final Set<Integer> sourceSet = Sets.newHashSet(0, 1, 2, 3, 4, 5);
final List<Integer> targetList = Lists.newArrayList(sourceSet);
}
@Test
public final void givenUsingGuava_whenListConvertedToSet_thenCorrect() {
final List<Integer> sourceList = Lists.newArrayList(0, 1, 2, 3, 4, 5);
final Set<Integer> targetSet = Sets.newHashSet(sourceList);
}
@Test
public final void givenUsingCommonsCollections_whenListConvertedToSet_thenCorrect() {
final List<Integer> sourceList = Lists.newArrayList(0, 1, 2, 3, 4, 5);
final Set<Integer> targetSet = new HashSet<>(6);
CollectionUtils.addAll(targetSet, sourceList);
}
@Test
public final void givenUsingCommonsCollections_whenSetConvertedToList_thenCorrect() {
final Set<Integer> sourceSet = Sets.newHashSet(0, 1, 2, 3, 4, 5);
final List<Integer> targetList = new ArrayList<>(6);
CollectionUtils.addAll(targetList, sourceSet);
}
}

View File

@ -8,7 +8,7 @@ This module contains articles about Java 11 core features
- [Java 11 Local Variable Syntax for Lambda Parameters](https://www.baeldung.com/java-var-lambda-params)
- [Java 11 String API Additions](https://www.baeldung.com/java-11-string-api)
- [Java 11 Nest Based Access Control](https://www.baeldung.com/java-nest-based-access-control)
- [Exploring the New HTTP Client in Java 9 and 11](https://www.baeldung.com/java-9-http-client)
- [Exploring the New HTTP Client in Java](https://www.baeldung.com/java-9-http-client)
- [An Introduction to Epsilon GC: A No-Op Experimental Garbage Collector](https://www.baeldung.com/jvm-epsilon-gc-garbage-collector)
- [Guide to jlink](https://www.baeldung.com/jlink)
- [Negate a Predicate Method Reference with Java 11](https://www.baeldung.com/java-negate-predicate-method-reference)

View File

@ -31,6 +31,6 @@ public class UseDateTimeFormatterUnitTest {
public void givenALocalDate_whenFormattingWithStyleAndLocale_thenPass() {
String result = subject.formatWithStyleAndLocale(localDateTime, FormatStyle.MEDIUM, Locale.UK);
assertThat(result).isEqualTo("25 Jan 2015, 06:30:00");
assertThat(result).isEqualTo("25-Jan-2015 06:30:00");
}
}

View File

@ -3,6 +3,7 @@ package com.baeldung.datetime;
import static org.assertj.core.api.Assertions.assertThat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
@ -24,10 +25,11 @@ public class UseToInstantUnitTest {
@Test
public void givenADate_whenConvertingToLocalDate_thenAsExpected() {
Date givenDate = new Date(1465817690000L);
LocalDateTime currentDateTime = LocalDateTime.now();
Date givenDate = Date.from(currentDateTime.atZone(ZoneId.systemDefault()).toInstant());
LocalDateTime localDateTime = subject.convertDateToLocalDate(givenDate);
assertThat(localDateTime).isEqualTo("2016-06-13T13:34:50");
assertThat(localDateTime).isEqualTo(currentDateTime);
}
}

View File

@ -54,7 +54,7 @@ public class UseZonedDateTimeUnitTest {
@Test
public void givenAStringWithTimeZone_whenParsing_thenEqualsExpected() {
ZonedDateTime resultFromString = zonedDateTime.getZonedDateTimeUsingParseMethod("2015-05-03T10:15:30+01:00[Europe/Paris]");
ZonedDateTime resultFromLocalDateTime = ZonedDateTime.of(2015, 5, 3, 11, 15, 30, 0, ZoneId.of("Europe/Paris"));
ZonedDateTime resultFromLocalDateTime = ZonedDateTime.of(2015, 5, 3, 10, 15, 30, 0, ZoneId.of("Europe/Paris"));
assertThat(resultFromString.getZone()).isEqualTo(ZoneId.of("Europe/Paris"));
assertThat(resultFromLocalDateTime.getZone()).isEqualTo(ZoneId.of("Europe/Paris"));

View File

@ -13,3 +13,5 @@ This module contains articles about core Java features that have been introduced
- [Java 9 Platform Logging API](https://www.baeldung.com/java-9-logging-api)
- [Java 9 Reactive Streams](https://www.baeldung.com/java-9-reactive-streams)
- [Multi-Release JAR Files with Maven](https://www.baeldung.com/maven-multi-release-jars)
- [The Difference between RxJava API and the Java 9 Flow API](https://www.baeldung.com/rxjava-vs-java-flow-api)
- [How to Get a Name of a Method Being Executed?](https://www.baeldung.com/java-name-of-executing-method)

View File

@ -9,3 +9,4 @@ This module contains articles about Java 9 core features
- [Iterate Through a Range of Dates in Java](https://www.baeldung.com/java-iterate-date-range)
- [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap)
- [Immutable ArrayList in Java](https://www.baeldung.com/java-immutable-list)
- [Easy Ways to Write a Java InputStream to an OutputStream](https://www.baeldung.com/java-inputstream-to-outputstream)

View File

@ -5,4 +5,4 @@ This module contains complete guides about arrays in Java
### Relevant Articles:
- [Arrays in Java: A Reference Guide](https://www.baeldung.com/java-arrays-guide)
- [Guide to the java.util.Arrays Class](https://www.baeldung.com/java-util-arrays)
- [What is [Ljava.lang.Object;?]](https://www.baeldung.com/java-tostring-array)
- [What is \[Ljava.lang.Object;?](https://www.baeldung.com/java-tostring-array)

View File

@ -3,7 +3,9 @@
This module contains articles about advanced operations on arrays in Java. They assume some background knowledge with arrays in Java.
### Relevant Articles:
- [How to Copy an Array in Java](https://www.baeldung.com/java-array-copy)
- [Arrays.deepEquals](https://www.baeldung.com/java-arrays-deepequals)
- [Find Sum and Average in a Java Array](https://www.baeldung.com/java-array-sum-average)
- [Intersection Between two Integer Arrays](https://www.baeldung.com/java-array-intersection)
- [Comparing Arrays in Java](https://www.baeldung.com/java-comparing-arrays)

View File

@ -0,0 +1,39 @@
package com.baeldung.arraycompare;
import java.util.Objects;
public class Plane {
private final String name;
private final String model;
public Plane(String name, String model) {
this.name = name;
this.model = model;
}
public String getName() {
return name;
}
public String getModel() {
return model;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Plane plane = (Plane) o;
return Objects.equals(name, plane.name) && Objects.equals(model, plane.model);
}
@Override
public int hashCode() {
return Objects.hash(name, model);
}
}

View File

@ -0,0 +1,30 @@
package com.baeldung.arraycompare;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import static org.assertj.core.api.Assertions.assertThat;
public class DeepEqualsCompareUnitTest {
@Test
public void givenSameContents_whenDeepEquals_thenTrue() {
final Plane[][] planes1 = new Plane[][] { new Plane[] { new Plane("Plane 1", "A320") },
new Plane[] { new Plane("Plane 2", "B738") } };
final Plane[][] planes2 = new Plane[][] { new Plane[] { new Plane("Plane 1", "A320") },
new Plane[] { new Plane("Plane 2", "B738") } };
assertThat(Arrays.deepEquals(planes1, planes2)).isTrue();
}
@Test
public void givenSameContentsWithDifferentOrder_whenDeepEquals_thenFalse() {
final Plane[][] planes1 = new Plane[][] { new Plane[] { new Plane("Plane 1", "A320") },
new Plane[] { new Plane("Plane 2", "B738") } };
final Plane[][] planes2 = new Plane[][] { new Plane[] { new Plane("Plane 2", "B738") },
new Plane[] { new Plane("Plane 1", "A320") } };
assertThat(Arrays.deepEquals(planes1, planes2)).isFalse();
}
}

View File

@ -0,0 +1,26 @@
package com.baeldung.arraycompare;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import static org.assertj.core.api.Assertions.assertThat;
public class EqualsCompareUnitTest {
@Test
public void givenSameContents_whenEquals_thenTrue() {
final String[] planes1 = new String[] { "A320", "B738", "A321", "A319", "B77W", "B737", "A333", "A332" };
final String[] planes2 = new String[] { "A320", "B738", "A321", "A319", "B77W", "B737", "A333", "A332" };
assertThat(Arrays.equals(planes1, planes2)).isTrue();
}
@Test
public void givenSameContentsDifferentOrder_whenEquals_thenFalse() {
final String[] planes1 = new String[] { "A320", "B738", "A321", "A319", "B77W", "B737", "A333", "A332" };
final String[] planes2 = new String[] { "B738", "A320", "A321", "A319", "B77W", "B737", "A333", "A332" };
assertThat(Arrays.equals(planes1, planes2)).isFalse();
}
}

View File

@ -0,0 +1,18 @@
package com.baeldung.arraycompare;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class LengthsCompareUnitTest {
@Test
public void givenSameContent_whenSizeCompare_thenTrue() {
final String[] planes1 = new String[] { "A320", "B738", "A321", "A319", "B77W", "B737", "A333", "A332" };
final Integer[] quantities = new Integer[] { 10, 12, 34, 45, 12, 43, 5, 2 };
assertThat(planes1).hasSize(8);
assertThat(quantities).hasSize(8);
}
}

View File

@ -0,0 +1,33 @@
package com.baeldung.arraycompare;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.Comparator;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertTrue;
public class OrderCompareUnitTest {
@Test
public void givenSameContentDifferentOrder_whenSortedAndDeepEquals_thenTrue() {
final Plane[][] planes1 = new Plane[][] {
new Plane[] { new Plane("Plane 1", "A320"), new Plane("Plane 2", "B738") } };
final Plane[][] planes2 = new Plane[][] {
new Plane[] { new Plane("Plane 2", "B738"), new Plane("Plane 1", "A320") } };
Comparator<Plane> planeComparator = (o1, o2) -> {
if (o1.getName()
.equals(o2.getName())) {
return o2.getModel()
.compareTo(o1.getModel());
}
return o2.getName()
.compareTo(o1.getName());
};
Arrays.sort(planes1[0], planeComparator);
Arrays.sort(planes2[0], planeComparator);
assertThat(Arrays.deepEquals(planes1, planes2)).isTrue();
}
}

View File

@ -0,0 +1,30 @@
package com.baeldung.arraycompare;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class ReferenceCompareUnitTest {
@Test
public void givenSameReferences_whenSame_thenTrue() {
final String[] planes1 = new String[] { "A320", "B738", "A321", "A319", "B77W", "B737", "A333", "A332" };
final String[] planes2 = planes1;
assertThat(planes1).isSameAs(planes2);
planes2[0] = "747";
assertThat(planes1).isSameAs(planes2);
assertThat(planes2[0]).isEqualTo("747");
assertThat(planes1[0]).isEqualTo("747");
}
@Test
public void givenSameContentDifferentReferences_whenSame_thenFalse() {
final String[] planes1 = new String[] { "A320", "B738", "A321", "A319", "B77W", "B737", "A333", "A332" };
final String[] planes2 = new String[] { "A320", "B738", "A321", "A319", "B77W", "B737", "A333", "A332" };
assertThat(planes1).isNotSameAs(planes2);
}
}

View File

@ -5,7 +5,16 @@ import org.apache.commons.lang3.ArrayUtils;
import org.junit.Before;
import org.junit.Test;
import java.util.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import static org.junit.Assert.assertTrue;
@ -138,7 +147,7 @@ public class JavaSortingUnitTest {
HashSet<Integer> descSortedIntegersSet = new LinkedHashSet<>(Arrays.asList(255, 200, 123, 89, 88, 66, 7, 5, 1));
ArrayList<Integer> list = new ArrayList<>(integersSet);
list.sort((i1, i2) -> i2 - i1);
list.sort(Comparator.reverseOrder());
integersSet = new LinkedHashSet<>(list);
assertTrue(Arrays.equals(integersSet.toArray(), descSortedIntegersSet.toArray()));

View File

@ -3,6 +3,7 @@
## Core Java Collections Cookbooks and Examples
### Relevant Articles:
- [Time Comparison of Arrays.sort(Object[]) and Arrays.sort(int[])](https://www.baeldung.com/arrays-sortobject-vs-sortint)
- [Java ArrayList vs Vector](https://www.baeldung.com/java-arraylist-vs-vector)
- [Differences Between HashMap and Hashtable](https://www.baeldung.com/hashmap-hashtable-differences)
@ -10,3 +11,5 @@
- [Performance of contains() in a HashSet vs ArrayList](https://www.baeldung.com/java-hashset-arraylist-contains-performance)
- [Fail-Safe Iterator vs Fail-Fast Iterator](https://www.baeldung.com/java-fail-safe-vs-fail-fast-iterator)
- [Quick Guide to the Java Stack](https://www.baeldung.com/java-stack)
- [Convert an Array of Primitives to a List](https://www.baeldung.com/java-primitive-array-to-list)
- [A Guide to BitSet in Java](https://www.baeldung.com/java-bitset)

View File

@ -16,6 +16,11 @@
</parent>
<dependencies>
<dependency>
<groupId>org.openjdk.jol</groupId>
<artifactId>jol-core</artifactId>
<version>${jol-core.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
@ -37,6 +42,7 @@
<properties>
<openjdk.jmh.version>1.19</openjdk.jmh.version>
<assertj.version>3.11.1</assertj.version>
<jol-core.version>0.10</jol-core.version>
</properties>
</project>

View File

@ -0,0 +1,178 @@
package com.baeldung.collections.bitset;
import org.junit.Test;
import org.openjdk.jol.info.ClassLayout;
import org.openjdk.jol.info.GraphLayout;
import java.util.BitSet;
import static org.assertj.core.api.Assertions.assertThat;
public class BitSetUnitTest {
@Test
public void givenBoolArray_whenMemoryLayout_thenConsumeMoreThanOneBit() {
boolean[] bits = new boolean[1024 * 1024];
System.out.println(ClassLayout.parseInstance(bits).toPrintable());
}
@Test
public void givenBitSet_whenMemoryLayout_thenConsumeOneBitPerFlag() {
BitSet bitSet = new BitSet(1024 * 1024);
System.out.println(GraphLayout.parseInstance(bitSet).toPrintable());
}
@Test
public void givenBitSet_whenSetting_thenShouldBeTrue() {
BitSet bitSet = new BitSet();
bitSet.set(10);
assertThat(bitSet.get(10)).isTrue();
bitSet.set(20, 30);
for (int i = 20; i <= 29; i++) {
assertThat(bitSet.get(i)).isTrue();
}
assertThat(bitSet.get(30)).isFalse();
bitSet.set(10, false);
assertThat(bitSet.get(10)).isFalse();
bitSet.set(20, 30, false);
for (int i = 20; i <= 30; i++) {
assertThat(bitSet.get(i)).isFalse();
}
}
@Test
public void givenBitSet_whenClearing_thenShouldBeFalse() {
BitSet bitSet = new BitSet();
bitSet.set(42);
assertThat(bitSet.get(42)).isTrue();
bitSet.clear(42);
assertThat(bitSet.get(42)).isFalse();
bitSet.set(10, 20);
for (int i = 10; i < 20; i++) {
assertThat(bitSet.get(i)).isTrue();
}
bitSet.clear(10, 20);
for (int i = 10; i < 20; i++) {
assertThat(bitSet.get(i)).isFalse();
}
bitSet.set(10, 20);
bitSet.clear();
for (int i = 0; i < 100; i++) {
assertThat(bitSet.get(i)).isFalse();
}
}
@Test
public void givenBitSet_whenGettingElements_thenShouldReturnRequestedBits() {
BitSet bitSet = new BitSet();
bitSet.set(42);
assertThat(bitSet.get(42)).isTrue();
assertThat(bitSet.get(43)).isFalse();
bitSet.set(10, 20);
BitSet newBitSet = bitSet.get(10, 20);
for (int i = 0; i < 10; i++) {
assertThat(newBitSet.get(i)).isTrue();
}
}
@Test
public void givenBitSet_whenFlip_thenTogglesTrueToFalseAndViceVersa() {
BitSet bitSet = new BitSet();
bitSet.set(42);
bitSet.flip(42);
assertThat(bitSet.get(42)).isFalse();
bitSet.flip(12);
assertThat(bitSet.get(12)).isTrue();
bitSet.flip(30, 40);
for (int i = 30; i < 40; i++) {
assertThat(bitSet.get(i)).isTrue();
}
}
@Test
public void givenBitSet_whenGettingTheSize_thenReturnsTheSize() {
BitSet defaultBitSet = new BitSet();
assertThat(defaultBitSet.size()).isEqualTo(64);
BitSet bitSet = new BitSet(1024);
assertThat(bitSet.size()).isEqualTo(1024);
assertThat(bitSet.cardinality()).isEqualTo(0);
bitSet.set(10, 30);
assertThat(bitSet.cardinality()).isEqualTo(30 - 10);
assertThat(bitSet.length()).isEqualTo(30);
bitSet.set(100);
assertThat(bitSet.length()).isEqualTo(101);
assertThat(bitSet.isEmpty()).isFalse();
bitSet.clear();
assertThat(bitSet.isEmpty()).isTrue();
}
@Test
public void givenBitSet_whenSetOperations_thenShouldReturnAnotherBitSet() {
BitSet first = new BitSet();
first.set(5, 10);
BitSet second = new BitSet();
second.set(7, 15);
assertThat(first.intersects(second)).isTrue();
first.and(second);
assertThat(first.get(7)).isTrue();
assertThat(first.get(8)).isTrue();
assertThat(first.get(9)).isTrue();
assertThat(first.get(10)).isFalse();
first.clear();
first.set(5, 10);
first.xor(second);
for (int i = 5; i < 7; i++) {
assertThat(first.get(i)).isTrue();
}
for (int i = 10; i < 15; i++) {
assertThat(first.get(i)).isTrue();
}
}
@Test
public void givenBitSet_whenStream_thenStreamsAllSetBits() {
BitSet bitSet = new BitSet();
bitSet.set(15, 25);
bitSet.stream().forEach(System.out::println);
assertThat(bitSet.stream().count()).isEqualTo(10);
}
@Test
public void givenBitSet_whenNextOrPrev_thenReturnsTheNextOrPrevClearOrSetBit() {
BitSet bitSet = new BitSet();
bitSet.set(15, 25);
assertThat(bitSet.nextSetBit(13)).isEqualTo(15);
assertThat(bitSet.nextSetBit(25)).isEqualTo(-1);
assertThat(bitSet.nextClearBit(23)).isEqualTo(25);
assertThat(bitSet.previousClearBit(24)).isEqualTo(14);
assertThat(bitSet.previousSetBit(29)).isEqualTo(24);
assertThat(bitSet.previousSetBit(14)).isEqualTo(-1);
}
}

View File

@ -10,4 +10,5 @@ This module contains articles about the Java List collection
- [Performance Comparison of Primitive Lists in Java](https://www.baeldung.com/java-list-primitive-performance)
- [Filtering a Java Collection by a List](https://www.baeldung.com/java-filter-collection-by-list)
- [How to Count Duplicate Elements in Arraylist](https://www.baeldung.com/java-count-duplicate-elements-arraylist)
- [Finding the Differences Between Two Lists in Java](https://www.baeldung.com/java-lists-difference)
- [[<-- Prev]](/core-java-modules/core-java-collections-list-2)

View File

@ -21,6 +21,12 @@
<artifactId>commons-collections4</artifactId>
<version>${commons-collections4.version}</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>

View File

@ -0,0 +1,96 @@
package com.baeldung.list.difference;
import com.google.common.collect.Sets;
import org.apache.commons.collections4.CollectionUtils;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import static org.junit.jupiter.api.Assertions.*;
import static org.assertj.core.api.Assertions.*;
public class FindDifferencesBetweenListsUnitTest {
private static final List<String> listOne = Arrays.asList("Jack", "Tom", "Sam", "John", "James", "Jack");
private static final List<String> listTwo = Arrays.asList("Jack", "Daniel", "Sam", "Alan", "James", "George");
@Test
public void givenLists_whenUsingPlainJavaImpl_thenDifferencesAreFound() {
List<String> differences = new ArrayList<>(listOne);
differences.removeAll(listTwo);
assertEquals(2, differences.size());
assertThat(differences).containsExactly("Tom", "John");
}
@Test
public void givenReverseLists_whenUsingPlainJavaImpl_thenDifferencesAreFound() {
List<String> differences = new ArrayList<>(listTwo);
differences.removeAll(listOne);
assertEquals(3, differences.size());
assertThat(differences).containsExactly("Daniel", "Alan", "George");
}
@Test
public void givenLists_whenUsingJavaStreams_thenDifferencesAreFound() {
List<String> differences = listOne.stream()
.filter(element -> !listTwo.contains(element))
.collect(Collectors.toList());
assertEquals(2, differences.size());
assertThat(differences).containsExactly("Tom", "John");
}
@Test
public void givenReverseLists_whenUsingJavaStreams_thenDifferencesAreFound() {
List<String> differences = listTwo.stream()
.filter(element -> !listOne.contains(element))
.collect(Collectors.toList());
assertEquals(3, differences.size());
assertThat(differences).containsExactly("Daniel", "Alan", "George");
}
@Test
public void givenLists_whenUsingGoogleGuava_thenDifferencesAreFound() {
List<String> differences = new ArrayList<>(Sets.difference(Sets.newHashSet(listOne), Sets.newHashSet(listTwo)));
assertEquals(2, differences.size());
assertThat(differences).containsExactlyInAnyOrder("Tom", "John");
}
@Test
public void givenReverseLists_whenUsingGoogleGuava_thenDifferencesAreFound() {
List<String> differences = new ArrayList<>(Sets.difference(Sets.newHashSet(listTwo), Sets.newHashSet(listOne)));
assertEquals(3, differences.size());
assertThat(differences).containsExactlyInAnyOrder("Daniel", "Alan", "George");
}
@Test
public void givenLists_whenUsingApacheCommons_thenDifferencesAreFound() {
List<String> differences = new ArrayList<>((CollectionUtils.removeAll(listOne, listTwo)));
assertEquals(2, differences.size());
assertThat(differences).containsExactly("Tom", "John");
}
@Test
public void givenReverseLists_whenUsingApacheCommons_thenDifferencesAreFound() {
List<String> differences = new ArrayList<>((CollectionUtils.removeAll(listTwo, listOne)));
assertEquals(3, differences.size());
assertThat(differences).containsExactly("Daniel", "Alan", "George");
}
@Test
public void givenLists_whenUsingPlainJavaImpl_thenDifferencesWithDuplicatesAreFound() {
List<String> differences = new ArrayList<>(listOne);
listTwo.forEach(differences::remove);
assertThat(differences).containsExactly("Tom", "John", "Jack");
}
@Test
public void givenLists_whenUsingApacheCommons_thenDifferencesWithDuplicatesAreFound() {
List<String> differences = new ArrayList<>(CollectionUtils.subtract(listOne, listTwo));
assertEquals(3, differences.size());
assertThat(differences).containsExactly("Tom", "John", "Jack");
}
}

View File

@ -21,20 +21,15 @@
<version>${eclipse-collections.version}</version>
</dependency>
<dependency>
<groupId>net.sf.trove4j</groupId>
<artifactId>trove4j</artifactId>
<version>${trove4j.version}</version>
<groupId>com.carrotsearch</groupId>
<artifactId>hppc</artifactId>
<version>${hppc.version}</version>
</dependency>
<dependency>
<groupId>it.unimi.dsi</groupId>
<artifactId>fastutil</artifactId>
<version>${fastutil.version}</version>
</dependency>
<dependency>
<groupId>colt</groupId>
<artifactId>colt</artifactId>
<version>${colt.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
@ -69,9 +64,8 @@
<commons-collections4.version>4.1</commons-collections4.version>
<avaitility.version>1.7.0</avaitility.version>
<eclipse-collections.version>8.2.0</eclipse-collections.version>
<trove4j.version>3.0.2</trove4j.version>
<hppc.version>0.7.2</hppc.version>
<fastutil.version>8.1.0</fastutil.version>
<colt.version>1.2.0</colt.version>
<assertj.version>3.11.1</assertj.version>
</properties>

View File

@ -1,29 +1,68 @@
package com.baeldung.map.primitives;
import cern.colt.map.AbstractIntDoubleMap;
import cern.colt.map.OpenIntDoubleHashMap;
import gnu.trove.map.TDoubleIntMap;
import gnu.trove.map.hash.TDoubleIntHashMap;
import com.carrotsearch.hppc.IntLongHashMap;
import com.carrotsearch.hppc.IntLongScatterMap;
import com.carrotsearch.hppc.IntObjectHashMap;
import com.carrotsearch.hppc.IntObjectMap;
import com.carrotsearch.hppc.IntObjectScatterMap;
import it.unimi.dsi.fastutil.ints.Int2BooleanMap;
import it.unimi.dsi.fastutil.ints.Int2BooleanMaps;
import it.unimi.dsi.fastutil.ints.Int2BooleanOpenHashMap;
import it.unimi.dsi.fastutil.ints.Int2BooleanSortedMap;
import it.unimi.dsi.fastutil.ints.Int2BooleanSortedMaps;
import it.unimi.dsi.fastutil.objects.ObjectIterator;
import org.eclipse.collections.api.map.primitive.ImmutableIntIntMap;
import org.eclipse.collections.api.map.primitive.MutableIntIntMap;
import org.eclipse.collections.api.map.primitive.MutableObjectDoubleMap;
import org.eclipse.collections.impl.factory.primitive.IntIntMaps;
import org.eclipse.collections.impl.factory.primitive.ObjectDoubleMaps;
import static java.lang.String.format;
import java.math.BigDecimal;
public class PrimitiveMaps {
public static void main(String[] args) {
hppcMap();
eclipseCollectionsMap();
troveMap();
coltMap();
fastutilMap();
}
private static void hppcMap() {
//Regular maps
IntLongHashMap intLongHashMap = new IntLongHashMap();
intLongHashMap.put(25,1L);
intLongHashMap.put(150,Long.MAX_VALUE);
intLongHashMap.put(1,0L);
intLongHashMap.get(150);
IntObjectMap<BigDecimal> intObjectMap = new IntObjectHashMap<BigDecimal>();
intObjectMap.put(1, BigDecimal.valueOf(1));
intObjectMap.put(2, BigDecimal.valueOf(2500));
BigDecimal value = intObjectMap.get(2);
//Scatter maps
IntLongScatterMap intLongScatterMap = new IntLongScatterMap();
intLongScatterMap.put(1, 1L);
intLongScatterMap.put(2, -2L);
intLongScatterMap.put(1000,0L);
intLongScatterMap.get(1000);
IntObjectScatterMap<BigDecimal> intObjectScatterMap = new IntObjectScatterMap<BigDecimal>();
intObjectScatterMap.put(1, BigDecimal.valueOf(1));
intObjectScatterMap.put(2, BigDecimal.valueOf(2500));
value = intObjectScatterMap.get(2);
}
private static void fastutilMap() {
Int2BooleanMap int2BooleanMap = new Int2BooleanOpenHashMap();
int2BooleanMap.put(1, true);
@ -32,13 +71,19 @@ public class PrimitiveMaps {
boolean value = int2BooleanMap.get(1);
Int2BooleanSortedMap int2BooleanSorted = Int2BooleanSortedMaps.EMPTY_MAP;
}
//Lambda style iteration
Int2BooleanMaps.fastForEach(int2BooleanMap, entry -> {
System.out.println(String.format("Key: %d, Value: %b",entry.getIntKey(),entry.getBooleanValue()));
});
//Iterator based loop
ObjectIterator<Int2BooleanMap.Entry> iterator = Int2BooleanMaps.fastIterator(int2BooleanMap);
while(iterator.hasNext()) {
Int2BooleanMap.Entry entry = iterator.next();
System.out.println(String.format("Key: %d, Value: %b",entry.getIntKey(),entry.getBooleanValue()));
}
private static void coltMap() {
AbstractIntDoubleMap map = new OpenIntDoubleHashMap();
map.put(1, 4.5);
double value = map.get(1);
}
private static void eclipseCollectionsMap() {
@ -53,17 +98,5 @@ public class PrimitiveMaps {
dObject.addToValue("stability", 0.8);
}
private static void troveMap() {
double[] doubles = new double[] {1.2, 4.5, 0.3};
int[] ints = new int[] {1, 4, 0};
TDoubleIntMap doubleIntMap = new TDoubleIntHashMap(doubles, ints);
doubleIntMap.put(1.2, 22);
doubleIntMap.put(4.5, 16);
doubleIntMap.adjustValue(1.2, 1);
doubleIntMap.adjustValue(4.5, 4);
doubleIntMap.adjustValue(0.3, 7);
}
}

View File

@ -15,4 +15,5 @@ This module contains articles about advanced topics about multithreading with co
- [The ABA Problem in Concurrency](https://www.baeldung.com/cs/aba-concurrency)
- [Introduction to Lock-Free Data Structures](https://www.baeldung.com/lock-free-programming)
- [Introduction to Exchanger in Java](https://www.baeldung.com/java-exchanger)
- [Why Not To Start A Thread In The Constructor?](https://www.baeldung.com/java-thread-constructor)
- [[<-- previous]](/core-java-modules/core-java-concurrency-advanced-2)

View File

@ -15,7 +15,15 @@ import java.util.logging.Logger;
import static org.junit.Assert.fail;
public class PrimeNumbersUnitManualTest {
/**
* This test expects the file target/test-classes/META-INF/BenchmarkList to be present.
*
* Before running the test ensure that the file is present.
* If not, please run mvn install on the module.
*
*/
public class PrimeNumbersManualTest {
private static Logger logger = Logger.getAnonymousLogger();

View File

@ -0,0 +1,25 @@
package com.baeldung.threadlocal;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class ThreadLocalAwareThreadPool extends ThreadPoolExecutor {
public ThreadLocalAwareThreadPool(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler);
}
@Override
protected void afterExecute(Runnable r, Throwable t) {
// Call remove on each ThreadLocal
}
}

View File

@ -3,10 +3,12 @@
This module contains articles about basic Java concurrency
### Relevant Articles:
- [How to Delay Code Execution in Java](https://www.baeldung.com/java-delay-code-execution)
- [wait and notify() Methods in Java](https://www.baeldung.com/java-wait-notify)
- [Difference Between Wait and Sleep in Java](https://www.baeldung.com/java-wait-and-sleep)
- [Guide to the Synchronized Keyword in Java](https://www.baeldung.com/java-synchronized)
- [Life Cycle of a Thread in Java](https://www.baeldung.com/java-thread-lifecycle)
- [Guide to AtomicMarkableReference](https://www.baeldung.com/java-atomicmarkablereference)
- [Why are Local Variables Thread-Safe in Java](https://www.baeldung.com/java-local-variables-thread-safe)
- [[<-- Prev]](/core-java-modules/core-java-concurrency-basic)

View File

@ -1,5 +1,8 @@
#Core Java Console
[Read and Write User Input in Java](http://www.baeldung.com/java-console-input-output)
[Formatting with printf() in Java](https://www.baeldung.com/java-printstream-printf)
[ASCII Art in Java](http://www.baeldung.com/ascii-art-in-java)
### Relevant Articles:
- [Read and Write User Input in Java](http://www.baeldung.com/java-console-input-output)
- [Formatting with printf() in Java](https://www.baeldung.com/java-printstream-printf)
- [ASCII Art in Java](http://www.baeldung.com/ascii-art-in-java)
- [System.console() vs. System.out](https://www.baeldung.com/java-system-console-vs-system-out)

View File

@ -2,6 +2,7 @@
This module contains articles about date operations in Java.
### Relevant Articles:
- [Get the Current Date Prior to Java 8](https://www.baeldung.com/java-get-the-current-date-legacy)
- [Skipping Weekends While Adding Days to LocalDate in Java 8](https://www.baeldung.com/java-localdate-add-days-skip-weekends)
- [Checking If Two Java Dates Are on the Same Day](https://www.baeldung.com/java-check-two-dates-on-same-day)
@ -9,4 +10,5 @@ This module contains articles about date operations in Java.
- [How to Set the JVM Time Zone](https://www.baeldung.com/java-jvm-time-zone)
- [How to determine day of week by passing specific date in Java?](https://www.baeldung.com/java-get-day-of-week)
- [Finding Leap Years in Java](https://www.baeldung.com/java-leap-year)
- [Getting the Week Number From Any Date](https://www.baeldung.com/java-get-week-number)
- [[<-- Prev]](/core-java-modules/core-java-date-operations-1)

View File

@ -12,3 +12,5 @@ This module contains articles about core java exceptions
- [Java Try with Resources](https://www.baeldung.com/java-try-with-resources)
- [Java Global Exception Handler](https://www.baeldung.com/java-global-exception-handler)
- [How to Find an Exceptions Root Cause in Java](https://www.baeldung.com/java-exception-root-cause)
- [Java IOException “Too many open files”](https://www.baeldung.com/java-too-many-open-files)
- [When Does Java Throw the ExceptionInInitializerError?](https://www.baeldung.com/java-exceptionininitializererror)

View File

@ -0,0 +1,3 @@
### Relevant Articles:
- [NoSuchMethodError in Java](https://www.baeldung.com/java-nosuchmethod-error)

View File

@ -0,0 +1,34 @@
<?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>
<groupId>com.baeldung.exceptions</groupId>
<artifactId>core-java-exceptions-3</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-exceptions-3</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../</relativePath>
</parent>
<dependencies>
<!-- test scoped -->
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj-core.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<!-- testing -->
<assertj-core.version>3.10.0</assertj-core.version>
</properties>
</project>

View File

@ -0,0 +1,11 @@
package com.baeldung.exceptions.nosuchmethoderror;
public class MainMenu {
public static void main(String[] args) {
System.out.println("Today's Specials: " + getSpecials());
}
public static String getSpecials() {
return SpecialToday.getDesert();
}
}

View File

@ -0,0 +1,8 @@
package com.baeldung.exceptions.nosuchmethoderror;
public class SpecialToday {
private static String desert = "Chocolate Cake";
public static String getDesert() {
return desert;
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.exceptions.nosuchmethoderror;
import static org.junit.Assert.assertNotNull;
import org.junit.jupiter.api.Test;
class MainMenuUnitTest {
@Test
void whenGetSpecials_thenNotNull() {
assertNotNull(MainMenu.getSpecials());
}
}

View File

@ -0,0 +1,2 @@
test-link*
0.*

View File

@ -3,5 +3,10 @@
This module contains articles about core Java input and output (IO)
### Relevant Articles:
- [Java Create a File](https://www.baeldung.com/java-how-to-create-a-file)
- [Check If a Directory Is Empty in Java](https://www.baeldung.com/java-check-empty-directory)
- [Check If a File or Directory Exists in Java](https://www.baeldung.com/java-file-directory-exists)
- [Copy a Directory in Java](https://www.baeldung.com/java-copy-directory)
- [Java Files Open Options](https://www.baeldung.com/java-file-options)
- [[<-- Prev]](/core-java-modules/core-java-io-2)

View File

@ -46,41 +46,14 @@
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/com.github.tomakehurst/wiremock -->
<dependency>
<groupId>com.github.tomakehurst</groupId>
<artifactId>wiremock</artifactId>
<version>${wiremock.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>core-java-io-3</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>${maven-javadoc-plugin.version}</version>
<configuration>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<assertj.version>3.6.1</assertj.version>
<maven-javadoc-plugin.version>3.0.0-M1</maven-javadoc-plugin.version>
<wiremock.version>2.26.3</wiremock.version>
</properties>
</project>

View File

@ -0,0 +1,15 @@
package com.baeldung.copydirectory;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
public class ApacheCommons {
public static void copyDirectory(String sourceDirectoryLocation, String destinationDirectoryLocation) throws IOException {
File sourceDirectory = new File(sourceDirectoryLocation);
File destinationDirectory = new File(destinationDirectoryLocation);
FileUtils.copyDirectory(sourceDirectory, destinationDirectory);
}
}

View File

@ -0,0 +1,38 @@
package com.baeldung.copydirectory;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class CoreOld {
public static void copyDirectoryJavaUnder7(File source, File destination) throws IOException {
if (source.isDirectory()) {
copyDirectory(source, destination);
} else {
copyFile(source, destination);
}
}
private static void copyDirectory(File sourceDirectory, File destinationDirectory) throws IOException {
if (!destinationDirectory.exists()) {
destinationDirectory.mkdir();
}
for (String f : sourceDirectory.list()) {
copyDirectoryJavaUnder7(new File(sourceDirectory, f), new File(destinationDirectory, f));
}
}
private static void copyFile(File sourceFile, File destinationFile) throws IOException {
try (InputStream in = new FileInputStream(sourceFile); OutputStream out = new FileOutputStream(destinationFile)) {
byte[] buf = new byte[1024];
int length;
while ((length = in.read(buf)) > 0) {
out.write(buf, 0, length);
}
}
}
}

View File

@ -0,0 +1,22 @@
package com.baeldung.copydirectory;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class JavaNio {
public static void copyDirectory(String sourceDirectoryLocation, String destinationDirectoryLocation) throws IOException {
Files.walk(Paths.get(sourceDirectoryLocation))
.forEach(source -> {
Path destination = Paths.get(destinationDirectoryLocation, source.toString()
.substring(sourceDirectoryLocation.length()));
try {
Files.copy(source, destination);
} catch (IOException e) {
e.printStackTrace();
}
});
}
}

View File

@ -0,0 +1,59 @@
package com.baeldung.copydirectory;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Comparator;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class ApacheCommonsUnitTest {
private final String sourceDirectoryLocation = "src/test/resources/sourceDirectory3";
private final String subDirectoryName = "/childDirectory";
private final String fileName = "/file.txt";
private final String destinationDirectoryLocation = "src/test/resources/destinationDirectory3";
@BeforeEach
public void createDirectoryWithSubdirectoryAndFile() throws IOException {
Files.createDirectories(Paths.get(sourceDirectoryLocation));
Files.createDirectories(Paths.get(sourceDirectoryLocation + subDirectoryName));
Files.createFile(Paths.get(sourceDirectoryLocation + subDirectoryName + fileName));
}
@Test
public void whenSourceDirectoryExists_thenDirectoryIsFullyCopied() throws IOException {
ApacheCommons.copyDirectory(sourceDirectoryLocation, destinationDirectoryLocation);
assertTrue(new File(destinationDirectoryLocation).exists());
assertTrue(new File(destinationDirectoryLocation + subDirectoryName).exists());
assertTrue(new File(destinationDirectoryLocation + subDirectoryName + fileName).exists());
}
@Test
public void whenSourceDirectoryDoesNotExist_thenExceptionIsThrown() {
assertThrows(Exception.class, () -> ApacheCommons.copyDirectory("nonExistingDirectory", destinationDirectoryLocation));
}
@AfterEach
public void cleanUp() throws IOException {
Files.walk(Paths.get(sourceDirectoryLocation))
.sorted(Comparator.reverseOrder())
.map(Path::toFile)
.forEach(File::delete);
if (new File(destinationDirectoryLocation).exists()) {
Files.walk(Paths.get(destinationDirectoryLocation))
.sorted(Comparator.reverseOrder())
.map(Path::toFile)
.forEach(File::delete);
}
}
}

View File

@ -0,0 +1,63 @@
package com.baeldung.copydirectory;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Comparator;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class CoreOldUnitTest {
private final String sourceDirectoryLocation = "src/test/resources/sourceDirectory1";
private final String subDirectoryName = "/childDirectory";
private final String fileName = "/file.txt";
private final String destinationDirectoryLocation = "src/test/resources/destinationDirectory1";
@BeforeEach
public void createDirectoryWithSubdirectoryAndFile() throws IOException {
Files.createDirectories(Paths.get(sourceDirectoryLocation));
Files.createDirectories(Paths.get(sourceDirectoryLocation + subDirectoryName));
Files.createFile(Paths.get(sourceDirectoryLocation + subDirectoryName + fileName));
}
@Test
public void whenSourceDirectoryExists_thenDirectoryIsFullyCopied() throws IOException {
File sourceDirectory = new File(sourceDirectoryLocation);
File destinationDirectory = new File(destinationDirectoryLocation);
CoreOld.copyDirectoryJavaUnder7(sourceDirectory, destinationDirectory);
assertTrue(new File(destinationDirectoryLocation).exists());
assertTrue(new File(destinationDirectoryLocation + subDirectoryName).exists());
assertTrue(new File(destinationDirectoryLocation + subDirectoryName + fileName).exists());
}
@Test
public void whenSourceDirectoryDoesNotExist_thenExceptionIsThrown() throws IOException {
File sourceDirectory = new File("nonExistingDirectory");
File destinationDirectory = new File(destinationDirectoryLocation);
assertThrows(IOException.class, () -> CoreOld.copyDirectoryJavaUnder7(sourceDirectory, destinationDirectory));
}
@AfterEach
public void cleanUp() throws IOException {
Files.walk(Paths.get(sourceDirectoryLocation))
.sorted(Comparator.reverseOrder())
.map(Path::toFile)
.forEach(File::delete);
if (new File(destinationDirectoryLocation).exists()) {
Files.walk(Paths.get(destinationDirectoryLocation))
.sorted(Comparator.reverseOrder())
.map(Path::toFile)
.forEach(File::delete);
}
}
}

View File

@ -0,0 +1,59 @@
package com.baeldung.copydirectory;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Comparator;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class JavaNioUnitTest {
private final String sourceDirectoryLocation = "src/test/resources/sourceDirectory2";
private final String subDirectoryName = "/childDirectory";
private final String fileName = "/file.txt";
private final String destinationDirectoryLocation = "src/test/resources/destinationDirectory2";
@BeforeEach
public void createDirectoryWithSubdirectoryAndFile() throws IOException {
Files.createDirectories(Paths.get(sourceDirectoryLocation));
Files.createDirectories(Paths.get(sourceDirectoryLocation + subDirectoryName));
Files.createFile(Paths.get(sourceDirectoryLocation + subDirectoryName + fileName));
}
@Test
public void whenSourceDirectoryExists_thenDirectoryIsFullyCopied() throws IOException {
JavaNio.copyDirectory(sourceDirectoryLocation, destinationDirectoryLocation);
assertTrue(new File(destinationDirectoryLocation).exists());
assertTrue(new File(destinationDirectoryLocation + subDirectoryName).exists());
assertTrue(new File(destinationDirectoryLocation + subDirectoryName + fileName).exists());
}
@Test
public void whenSourceDirectoryDoesNotExist_thenExceptionIsThrown() {
assertThrows(IOException.class, () -> JavaNio.copyDirectory("nonExistingDirectory", destinationDirectoryLocation));
}
@AfterEach
public void cleanUp() throws IOException {
Files.walk(Paths.get(sourceDirectoryLocation))
.sorted(Comparator.reverseOrder())
.map(Path::toFile)
.forEach(File::delete);
if (new File(destinationDirectoryLocation).exists()) {
Files.walk(Paths.get(destinationDirectoryLocation))
.sorted(Comparator.reverseOrder())
.map(Path::toFile)
.forEach(File::delete);
}
}
}

View File

@ -0,0 +1,63 @@
package com.baeldung.emptiness;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;
import static org.assertj.core.api.Assertions.assertThat;
public class DirectoryEmptinessUnitTest {
@Test
public void givenPath_whenInvalid_thenReturnsFalse() throws IOException {
assertThat(isEmpty(Paths.get("invalid-addr"))).isFalse();
}
@Test
public void givenPath_whenNotDirectory_thenReturnsFalse() throws IOException {
Path aFile = Paths.get(getClass().getResource("/notDir.txt").getPath());
assertThat(isEmpty(aFile)).isFalse();
}
@Test
public void givenPath_whenNotEmptyDir_thenReturnsFalse() throws IOException {
Path currentDir = new File("").toPath().toAbsolutePath();
assertThat(isEmpty(currentDir)).isFalse();
}
@Test
public void givenPath_whenIsEmpty_thenReturnsTrue() throws Exception {
Path path = Files.createTempDirectory("baeldung-empty");
assertThat(isEmpty(path)).isTrue();
}
private static boolean isEmpty(Path path) throws IOException {
if (Files.isDirectory(path)) {
try (DirectoryStream<Path> directory = Files.newDirectoryStream(path)) {
return !directory.iterator().hasNext();
}
}
return false;
}
private static boolean isEmpty2(Path path) throws IOException {
if (Files.isDirectory(path)) {
try (Stream<Path> entries = Files.list(path)) {
return !entries.findFirst().isPresent();
}
}
return false;
}
private static boolean isEmptyInefficient(Path path) {
return path.toFile().listFiles().length == 0;
}
}

View File

@ -0,0 +1,91 @@
package com.baeldung.existence;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.ThreadLocalRandom;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class ExistenceUnitTest {
@Test
public void givenFile_whenDoesNotExist_thenFilesReturnsFalse() {
Path path = Paths.get("does-not-exist.txt");
assertFalse(Files.exists(path));
assertTrue(Files.notExists(path));
}
@Test
public void givenFile_whenExists_thenFilesShouldReturnTrue() throws IOException {
Path tempFile = Files.createTempFile("baeldung", "exist-nio");
assertTrue(Files.exists(tempFile));
assertFalse(Files.notExists(tempFile));
Path tempDirectory = Files.createTempDirectory("baeldung-exists");
assertTrue(Files.exists(tempDirectory));
assertFalse(Files.notExists(tempDirectory));
assertTrue(Files.isDirectory(tempDirectory));
assertFalse(Files.isDirectory(tempFile));
assertTrue(Files.isRegularFile(tempFile));
assertTrue(Files.isReadable(tempFile));
Files.deleteIfExists(tempFile);
Files.deleteIfExists(tempDirectory);
}
@Test
public void givenSymbolicLink_whenTargetDoesNotExists_thenFollowOrNotBasedOnTheOptions() throws IOException {
Path target = Files.createTempFile("baeldung", "target");
Path symbol = Paths.get("test-link-" + ThreadLocalRandom.current().nextInt());
Path symbolicLink = Files.createSymbolicLink(symbol, target);
assertTrue(Files.exists(symbolicLink));
assertTrue(Files.isSymbolicLink(symbolicLink));
assertFalse(Files.isSymbolicLink(target));
Files.deleteIfExists(target);
assertFalse(Files.exists(symbolicLink));
assertTrue(Files.exists(symbolicLink, LinkOption.NOFOLLOW_LINKS));
Files.deleteIfExists(symbolicLink);
}
@Test
public void givenFile_whenDoesNotExist_thenFileReturnsFalse() {
assertFalse(new File("invalid").exists());
assertFalse(new File("invalid").isFile());
}
@Test
public void givenFile_whenExist_thenShouldReturnTrue() throws IOException {
Path tempFilePath = Files.createTempFile("baeldung", "exist-io");
Path tempDirectoryPath = Files.createTempDirectory("baeldung-exists-io");
File tempFile = new File(tempFilePath.toString());
File tempDirectory = new File(tempDirectoryPath.toString());
assertTrue(tempFile.exists());
assertTrue(tempDirectory.exists());
assertTrue(tempFile.isFile());
assertFalse(tempDirectory.isFile());
assertTrue(tempDirectory.isDirectory());
assertFalse(tempFile.isDirectory());
assertTrue(tempFile.canRead());
Files.deleteIfExists(tempFilePath);
Files.deleteIfExists(tempDirectoryPath);
}
}

View File

@ -0,0 +1,82 @@
package com.baeldung.linenumber;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.junit.Test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Stream;
import static org.junit.Assert.assertEquals;
public class LineAtGivenNumberUnitTest {
private static final String FILE_PATH = "src/test/resources/linesInput.txt";
@Test
public void givenFile_whenUsingBufferedReader_thenExtractedLineIsCorrect() throws IOException {
try (BufferedReader br = Files.newBufferedReader(Paths.get(FILE_PATH))) {
for (int i = 0; i < 3; i++) {
br.readLine();
}
String extractedLine = br.readLine();
assertEquals("Line 4", extractedLine);
}
}
@Test
public void givenFile_whenUsingScanner_thenExtractedLineIsCorrect() throws IOException {
try (Scanner scanner = new Scanner(new File(FILE_PATH))) {
for (int i = 0; i < 3; i++) {
scanner.nextLine();
}
String extractedLine = scanner.nextLine();
assertEquals("Line 4", extractedLine);
}
}
@Test
public void givenSmallFile_whenUsingFilesAPI_thenExtractedLineIsCorrect() throws IOException {
String extractedLine = Files.readAllLines(Paths.get(FILE_PATH)).get(4);
assertEquals("Line 5", extractedLine);
}
@Test
public void givenLargeFile_whenUsingFilesAPI_thenExtractedLineIsCorrect() throws IOException {
try (Stream<String> lines = Files.lines(Paths.get(FILE_PATH))) {
String extractedLine = lines.skip(4).findFirst().get();
assertEquals("Line 5", extractedLine);
}
}
@Test
public void givenFile_whenUsingFileUtils_thenExtractedLineIsCorrect() throws IOException {
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("linesInput.txt").getFile());
List<String> lines = FileUtils.readLines(file, "UTF-8");
String extractedLine = lines.get(0);
assertEquals("Line 1", extractedLine);
}
@Test
public void givenFile_whenUsingIOUtils_thenExtractedLineIsCorrect() throws IOException {
String fileContent = IOUtils.toString(new FileInputStream(FILE_PATH), StandardCharsets.UTF_8);
String extractedLine = fileContent.split(System.lineSeparator())[0];
assertEquals("Line 1", extractedLine);
}
}

View File

@ -0,0 +1,96 @@
package com.baeldung.openoptions;
import org.hamcrest.CoreMatchers;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import static org.junit.Assert.*;
public class OpenOptionsUnitTest {
private static final String HOME = System.getProperty("user.home");
private static final String DUMMY_FILE_NAME = "sample.txt";
private static final String EXISTING_FILE_NAME = "existingFile.txt";
private static final String DUMMY_TEXT = "This is a sample text.";
private static final String ANOTHER_DUMMY_TEXT = "This is a another text.";
@BeforeClass
public static void beforeAll() throws IOException {
Path path = Paths.get(HOME, DUMMY_FILE_NAME);
try (OutputStream out = Files.newOutputStream(path)) {
out.write(DUMMY_TEXT.getBytes());
}
Files.createFile(Paths.get(HOME, EXISTING_FILE_NAME));
}
@AfterClass
public static void afterAll() throws IOException {
Files.delete(Paths.get(HOME, "newfile.txt"));
Files.delete(Paths.get(HOME, "sparse.txt"));
Files.delete(Paths.get(HOME, DUMMY_FILE_NAME));
}
@Test
public void givenExistingPath_whenCreateNewFile_thenCorrect() throws IOException {
Path path = Paths.get(HOME, "newfile.txt");
assertFalse(Files.exists(path));
Files.write(path, DUMMY_TEXT.getBytes(), StandardOpenOption.CREATE);
assertTrue(Files.exists(path));
}
@Test
public void givenExistingPath_whenReadExistingFile_thenCorrect() throws IOException {
Path path = Paths.get(HOME, DUMMY_FILE_NAME);
try (InputStream in = Files.newInputStream(path); BufferedReader reader = new BufferedReader(new InputStreamReader(in))) {
String line;
while ((line = reader.readLine()) != null) {
assertThat(line, CoreMatchers.containsString(DUMMY_TEXT));
}
}
}
@Test
public void givenExistingPath_whenWriteToExistingFile_thenCorrect() throws IOException {
Path path = Paths.get(HOME, DUMMY_FILE_NAME);
try (OutputStream out = Files.newOutputStream(path, StandardOpenOption.APPEND, StandardOpenOption.WRITE)) {
out.write(ANOTHER_DUMMY_TEXT.getBytes());
}
}
@Test
public void givenExistingPath_whenCreateSparseFile_thenCorrect() throws IOException {
Path path = Paths.get(HOME, "sparse.txt");
Files.write(path, DUMMY_TEXT.getBytes(), StandardOpenOption.CREATE_NEW, StandardOpenOption.SPARSE);
}
@Test
public void givenExistingPath_whenDeleteOnClose_thenCorrect() throws IOException {
Path path = Paths.get(HOME, EXISTING_FILE_NAME);
assertTrue(Files.exists(path)); // file was already created and exists
try (OutputStream out = Files.newOutputStream(path, StandardOpenOption.APPEND, StandardOpenOption.WRITE, StandardOpenOption.DELETE_ON_CLOSE)) {
out.write(ANOTHER_DUMMY_TEXT.getBytes());
}
assertFalse(Files.exists(path)); // file is deleted
}
@Test
public void givenExistingPath_whenWriteAndSync_thenCorrect() throws IOException {
Path path = Paths.get(HOME, DUMMY_FILE_NAME);
Files.write(path, ANOTHER_DUMMY_TEXT.getBytes(), StandardOpenOption.APPEND, StandardOpenOption.WRITE, StandardOpenOption.SYNC);
}
}

View File

@ -0,0 +1,5 @@
Line 1
Line 2
Line 3
Line 4
Line 5

View File

@ -8,4 +8,7 @@ This module contains articles about working with the Java Virtual Machine (JVM).
- [Measuring Object Sizes in the JVM](https://www.baeldung.com/jvm-measuring-object-sizes)
- [Adding Shutdown Hooks for JVM Applications](https://www.baeldung.com/jvm-shutdown-hooks)
- [boolean and boolean[] Memory Layout in the JVM](https://www.baeldung.com/jvm-boolean-memory-layout)
- More articles: [[<-- prev]](/core-java-modules/core-java-jvm)
- [Where Is the Array Length Stored in JVM?](https://www.baeldung.com/java-jvm-array-length)
- [Memory Address of Objects in Java](https://www.baeldung.com/java-object-memory-address)
- [List All Classes Loaded in a Specific Class Loader](https://www.baeldung.com/java-list-classes-class-loader)
- More articles: [[<-- prev]](/core-java-modules/core-java-jvm)

View File

@ -0,0 +1,19 @@
package com.baeldung.loadedclasslisting;
import java.util.Arrays;
public class Launcher {
public static void main(String[] args) {
printClassesLoadedBy("BOOTSTRAP");
printClassesLoadedBy("SYSTEM");
printClassesLoadedBy("EXTENSION");
}
private static void printClassesLoadedBy(String classLoaderType) {
System.out.println(classLoaderType + " ClassLoader : ");
Class<?>[] classes = ListLoadedClassesAgent.listLoadedClasses(classLoaderType);
Arrays.asList(classes)
.forEach(clazz -> System.out.println(clazz.getCanonicalName()));
}
}

View File

@ -0,0 +1,40 @@
package com.baeldung.loadedclasslisting;
import java.lang.instrument.Instrumentation;
public class ListLoadedClassesAgent {
private static Instrumentation instrumentation;
public static void premain(String agentArgs, Instrumentation instrumentation) {
ListLoadedClassesAgent.instrumentation = instrumentation;
}
public static Class<?>[] listLoadedClasses(String classLoaderType) {
if (instrumentation == null) {
throw new IllegalStateException(
"ListLoadedClassesAgent is not initialized.");
}
return instrumentation.getInitiatedClasses(
getClassLoader(classLoaderType));
}
private static ClassLoader getClassLoader(String classLoaderType) {
ClassLoader classLoader = null;
switch (classLoaderType) {
case "SYSTEM":
classLoader = ClassLoader.getSystemClassLoader();
break;
case "EXTENSION":
classLoader = ClassLoader.getSystemClassLoader().getParent();
break;
// passing a null value to the Instrumentation : getInitiatedClasses method
// defaults to the bootstrap class loader
case "BOOTSTRAP":
break;
default:
break;
}
return classLoader;
}
}

View File

@ -0,0 +1 @@
Premain-Class: com.baeldung.loadedclasslisting.ListLoadedClassesAgent

View File

@ -37,7 +37,7 @@ public class Human {
public static int compareByNameThenAge(final Human lhs, final Human rhs) {
if (lhs.name.equals(rhs.name)) {
return lhs.age - rhs.age;
return Integer.compare(lhs.age, rhs.age);
} else {
return lhs.name.compareTo(rhs.name);
}

View File

@ -6,8 +6,11 @@ public interface Bar {
String method(String string);
default String defaultMethod() {
return "String from Bar";
default String defaultBar() {
return "Default String from Bar";
}
default String defaultCommon() {
return "Default Common from Bar";
}
}

View File

@ -6,7 +6,11 @@ public interface Baz {
String method(String string);
default String defaultMethod() {
return "String from Baz";
default String defaultBaz() {
return "Default String from Baz";
}
default String defaultCommon(){
return "Default Common from Baz";
}
}

View File

@ -5,8 +5,7 @@ package com.baeldung.java8.lambda.tips;
public interface FooExtended extends Baz, Bar {
@Override
default String defaultMethod() {
return Bar.super.defaultMethod();
default String defaultCommon() {
return Bar.super.defaultCommon();
}
}

View File

@ -54,7 +54,7 @@ public class Java8SortUnitTest {
final List<Human> humans = Lists.newArrayList(new Human("Sarah", 12), new Human("Sarah", 10), new Human("Zack", 12));
humans.sort((lhs, rhs) -> {
if (lhs.getName().equals(rhs.getName())) {
return lhs.getAge() - rhs.getAge();
return Integer.compare(lhs.getAge(), rhs.getAge());
} else {
return lhs.getName().compareTo(rhs.getName());
}

View File

@ -39,9 +39,9 @@ public class Java8FunctionalInteracesLambdasUnitTest {
@Test
public void defaultMethodFromExtendedInterface_whenReturnDefiniteString_thenCorrect() {
final FooExtended fooExtended = string -> string;
final String result = fooExtended.defaultMethod();
final String result = fooExtended.defaultCommon();
assertEquals("String from Bar", result);
assertEquals("Default Common from Bar", result);
}
@Test

View File

@ -2,4 +2,7 @@
This module contains articles about core features in the Java language
- [Class.isInstance vs Class.isAssignableFrom](https://www.baeldung.com/java-isinstance-isassignablefrom)
- [Converting a Java String Into a Boolean](https://www.baeldung.com/java-string-to-boolean)
- [When are Static Variables Initialized in Java?](https://www.baeldung.com/java-static-variables-initialization)
- [[<-- Prev]](/core-java-modules/core-java-lang-2)

View File

@ -3,7 +3,9 @@
This module contains articles about methods in Java
### Relevant Articles:
- [Methods in Java](https://www.baeldung.com/java-methods)
- [Method Overloading and Overriding in Java](https://www.baeldung.com/java-method-overload-override)
- [Java equals() and hashCode() Contracts](https://www.baeldung.com/java-equals-hashcode-contracts)
- [Guide to hashCode() in Java](https://www.baeldung.com/java-hashcode)
- [The Covariant Return Type in Java](https://www.baeldung.com/java-covariant-return-type)

View File

@ -3,6 +3,7 @@
This module contains articles about types in Java
### Relevant Articles:
- [Java Classes and Objects](https://www.baeldung.com/java-classes-objects)
- [Guide to the this Java Keyword](https://www.baeldung.com/java-this)
- [Nested Classes in Java](https://www.baeldung.com/java-nested-classes)
@ -10,3 +11,4 @@ This module contains articles about types in Java
- [Iterating Over Enum Values in Java](https://www.baeldung.com/java-enum-iteration)
- [Attaching Values to Java Enum](https://www.baeldung.com/java-enum-values)
- [A Guide to Java Enums](https://www.baeldung.com/a-guide-to-java-enums)
- [Determine if an Object is of Primitive Type](https://www.baeldung.com/java-object-primitive-type)

View File

@ -12,4 +12,12 @@
<artifactId>core-java-lang-oop-types</artifactId>
<name>core-java-lang-oop-types</name>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,26 @@
package com.baeldung.primitivetype;
import java.util.HashMap;
import java.util.Map;
public class PrimitiveTypeUtil {
private static final Map<Class<?>, Class<?>> WRAPPER_TYPE_MAP;
static {
WRAPPER_TYPE_MAP = new HashMap<Class<?>, Class<?>>(16);
WRAPPER_TYPE_MAP.put(Integer.class, int.class);
WRAPPER_TYPE_MAP.put(Byte.class, byte.class);
WRAPPER_TYPE_MAP.put(Character.class, char.class);
WRAPPER_TYPE_MAP.put(Boolean.class, boolean.class);
WRAPPER_TYPE_MAP.put(Double.class, double.class);
WRAPPER_TYPE_MAP.put(Float.class, float.class);
WRAPPER_TYPE_MAP.put(Long.class, long.class);
WRAPPER_TYPE_MAP.put(Short.class, short.class);
WRAPPER_TYPE_MAP.put(Void.class, void.class);
}
public static boolean isPrimitiveType(Object source) {
return WRAPPER_TYPE_MAP.containsKey(source.getClass());
}
}

View File

@ -0,0 +1,34 @@
package com.baeldung.primitivetype;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.apache.commons.lang3.ClassUtils;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import com.google.common.primitives.Primitives;
public class PrimitiveTypeUnitTest {
@Test
public void givenAClass_whenCheckWithPrimitiveTypeUtil_thenShouldValidate() {
assertTrue(PrimitiveTypeUtil.isPrimitiveType(false));
assertTrue(PrimitiveTypeUtil.isPrimitiveType(1L));
assertFalse(PrimitiveTypeUtil.isPrimitiveType(StringUtils.EMPTY));
}
@Test
public void givenAClass_whenCheckWithCommonsLang_thenShouldValidate() {
assertTrue(ClassUtils.isPrimitiveOrWrapper(Boolean.FALSE.getClass()));
assertTrue(ClassUtils.isPrimitiveOrWrapper(boolean.class));
assertFalse(ClassUtils.isPrimitiveOrWrapper(StringUtils.EMPTY.getClass()));
}
@Test
public void givenAClass_whenCheckWithGuava_thenShouldValidate() {
assertTrue(Primitives.isWrapperType(Boolean.FALSE.getClass()));
assertFalse(Primitives.isWrapperType(StringUtils.EMPTY.getClass()));
assertFalse(Primitives.isWrapperType(Boolean.TYPE.getClass()));
}
}

View File

@ -45,7 +45,7 @@ public class Player implements Comparable<Player> {
@Override
public int compareTo(Player otherPlayer) {
return (this.getRanking() - otherPlayer.getRanking());
return Integer.compare(getRanking(), otherPlayer.getRanking());
}
}

View File

@ -6,7 +6,7 @@ public class PlayerAgeComparator implements Comparator<Player> {
@Override
public int compare(Player firstPlayer, Player secondPlayer) {
return (firstPlayer.getAge() - secondPlayer.getAge());
return Integer.compare(firstPlayer.getAge(), secondPlayer.getAge());
}
}

View File

@ -6,7 +6,7 @@ public class PlayerRankingComparator implements Comparator<Player> {
@Override
public int compare(Player firstPlayer, Player secondPlayer) {
return (firstPlayer.getRanking() - secondPlayer.getRanking());
return Integer.compare(firstPlayer.getRanking(), secondPlayer.getRanking());
}
}

View File

@ -0,0 +1,26 @@
package com.baeldung.comparator;
import org.junit.Test;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import static org.junit.Assert.assertEquals;
public class AvoidingSubtractionUnitTest {
@Test
public void givenTwoPlayers_whenUsingSubtraction_thenOverflow() {
Comparator<Player> comparator = (p1, p2) -> p1.getRanking() - p2.getRanking();
Player player1 = new Player(59, "John", Integer.MAX_VALUE);
Player player2 = new Player(67, "Roger", -1);
List<Player> players = Arrays.asList(player1, player2);
players.sort(comparator);
System.out.println(players);
assertEquals("John", players.get(0).getName());
assertEquals("Roger", players.get(1).getName());
}
}

View File

@ -1,14 +1,14 @@
package com.baeldung.comparator;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class Java8ComparatorUnitTest {
@ -28,7 +28,7 @@ public class Java8ComparatorUnitTest {
@Test
public void whenComparing_UsingLambda_thenSorted() {
System.out.println("************** Java 8 Comaparator **************");
Comparator<Player> byRanking = (Player player1, Player player2) -> player1.getRanking() - player2.getRanking();
Comparator<Player> byRanking = (Player player1, Player player2) -> Integer.compare(player1.getRanking(), player2.getRanking());
System.out.println("Before Sorting : " + footballTeam);
Collections.sort(footballTeam, byRanking);

View File

@ -12,4 +12,5 @@ This module contains articles about networking in Java
- [Authentication with HttpUrlConnection](https://www.baeldung.com/java-http-url-connection)
- [Download a File from an URL in Java](https://www.baeldung.com/java-download-file)
- [Handling java.net.ConnectException](https://www.baeldung.com/java-net-connectexception)
- [Getting MAC addresses in Java](https://www.baeldung.com/java-mac-address)
- [[<-- Prev]](/core-java-modules/core-java-networking)

View File

@ -49,11 +49,11 @@ public class EchoServer {
if (new String(buffer.array()).trim().equals(POISON_PILL)) {
client.close();
System.out.println("Not accepting client messages anymore");
} else {
buffer.flip();
client.write(buffer);
buffer.clear();
}
buffer.flip();
client.write(buffer);
buffer.clear();
}
private static void register(Selector selector, ServerSocketChannel serverSocket) throws IOException {

View File

@ -12,5 +12,6 @@ This module contains articles about working with the operating system (OS) in Ja
- [How to Print Screen in Java](http://www.baeldung.com/print-screen-in-java)
- [Pattern Search with Grep in Java](http://www.baeldung.com/grep-in-java)
- [How to Run a Shell Command in Java](http://www.baeldung.com/run-shell-command-in-java)
- [Taking Screenshots Using Java](https://www.baeldung.com/java-taking-screenshots)
This module uses Java 9, so make sure to have the JDK 9 installed to run it.
This module uses Java 9, so make sure to have the JDK 9 installed to run it.

View File

@ -0,0 +1,51 @@
import javax.imageio.ImageIO;
import java.awt.Component;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
public class ScreenshotUnitTest {
@Test
public void givenMainScreen_whenTakeScreenshot_thenSaveToFile() throws Exception {
Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
BufferedImage capture = new Robot().createScreenCapture(screenRect);
File imageFile = File.createTempFile("single-screen", "bmp");
ImageIO.write(capture, "bmp", imageFile);
assertTrue(imageFile.exists());
}
@Test
public void givenMultipleScreens_whenTakeScreenshot_thenSaveToFile() throws Exception {
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] screens = ge.getScreenDevices();
Rectangle allScreenBounds = new Rectangle();
for (GraphicsDevice screen : screens) {
Rectangle screenBounds = screen.getDefaultConfiguration().getBounds();
allScreenBounds.width += screenBounds.width;
allScreenBounds.height = Math.max(allScreenBounds.height, screenBounds.height);
}
BufferedImage capture = new Robot().createScreenCapture(allScreenBounds);
File imageFile = File.createTempFile("all-screens", "bmp");
ImageIO.write(capture, "bmp", imageFile);
assertTrue(imageFile.exists());
}
@Test
public void givenComponent_whenTakeScreenshot_thenSaveToFile(Component component) throws Exception {
Rectangle componentRect = component.getBounds();
BufferedImage bufferedImage = new BufferedImage(componentRect.width, componentRect.height, BufferedImage.TYPE_INT_ARGB);
component.paint(bufferedImage.getGraphics());
File imageFile = File.createTempFile("component-screenshot", "bmp");
ImageIO.write(bufferedImage, "bmp", imageFile);
assertTrue(imageFile.exists());
}
}

View File

@ -0,0 +1,4 @@
### Relevant Articles:
- [Reading the Value of private Fields from a Different Class in Java](https://www.baeldung.com/java-reflection-read-private-field-value)
- [Set Field Value With Reflection](https://www.baeldung.com/java-set-private-field-value)

View File

@ -0,0 +1,183 @@
package com.baeldung.reflection.set.fields;
import java.lang.reflect.Field;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import com.baeldung.reflection.access.privatefields.Person;
public class SetFieldsUsingReflectionUnitTest {
@Test
public void whenSetIntegerFields_thenSuccess() throws Exception {
Person person = new Person();
Field ageField = person.getClass()
.getDeclaredField("age");
ageField.setAccessible(true);
byte age = 26;
ageField.setByte(person, age);
Assertions.assertEquals(age, person.getAge());
Field uidNumberField = person.getClass()
.getDeclaredField("uidNumber");
uidNumberField.setAccessible(true);
short uidNumber = 5555;
uidNumberField.setShort(person, uidNumber);
Assertions.assertEquals(uidNumber, person.getUidNumber());
Field pinCodeField = person.getClass()
.getDeclaredField("pinCode");
pinCodeField.setAccessible(true);
int pinCode = 411057;
pinCodeField.setInt(person, pinCode);
Assertions.assertEquals(pinCode, person.getPinCode());
Field contactNumberField = person.getClass()
.getDeclaredField("contactNumber");
contactNumberField.setAccessible(true);
long contactNumber = 123456789L;
contactNumberField.setLong(person, contactNumber);
Assertions.assertEquals(contactNumber, person.getContactNumber());
}
@Test
public void whenDoUnboxing_thenSuccess() throws Exception {
Person person = new Person();
Field pinCodeField = person.getClass()
.getDeclaredField("pinCode");
pinCodeField.setAccessible(true);
Integer pinCode = 411057;
pinCodeField.setInt(person, pinCode);
Assertions.assertEquals(pinCode, person.getPinCode());
}
@Test
public void whenDoNarrowing_thenSuccess() throws Exception {
Person person = new Person();
Field pinCodeField = person.getClass()
.getDeclaredField("pinCode");
pinCodeField.setAccessible(true);
short pinCode = 4110;
pinCodeField.setInt(person, pinCode);
Assertions.assertEquals(pinCode, person.getPinCode());
}
@Test
public void whenSetFloatingTypeFields_thenSuccess() throws Exception {
Person person = new Person();
Field heightField = person.getClass()
.getDeclaredField("height");
heightField.setAccessible(true);
float height = 6.1242f;
heightField.setFloat(person, height);
Assertions.assertEquals(height, person.getHeight());
Field weightField = person.getClass()
.getDeclaredField("weight");
weightField.setAccessible(true);
double weight = 75.2564;
weightField.setDouble(person, weight);
Assertions.assertEquals(weight, person.getWeight());
}
@Test
public void whenSetCharacterFields_thenSuccess() throws Exception {
Person person = new Person();
Field genderField = person.getClass()
.getDeclaredField("gender");
genderField.setAccessible(true);
char gender = 'M';
genderField.setChar(person, gender);
Assertions.assertEquals(gender, person.getGender());
}
@Test
public void whenSetBooleanFields_thenSuccess() throws Exception {
Person person = new Person();
Field activeField = person.getClass()
.getDeclaredField("active");
activeField.setAccessible(true);
activeField.setBoolean(person, true);
Assertions.assertTrue(person.isActive());
}
@Test
public void whenSetObjectFields_thenSuccess() throws Exception {
Person person = new Person();
Field nameField = person.getClass()
.getDeclaredField("name");
nameField.setAccessible(true);
String name = "Umang Budhwar";
nameField.set(person, name);
Assertions.assertEquals(name, person.getName());
}
@Test
public void givenInt_whenSetStringField_thenIllegalArgumentException() throws Exception {
Person person = new Person();
Field nameField = person.getClass()
.getDeclaredField("name");
nameField.setAccessible(true);
Assertions.assertThrows(IllegalArgumentException.class, () -> nameField.setInt(person, 26));
}
@Test
public void givenInt_whenSetLongField_thenIllegalArgumentException() throws Exception {
Person person = new Person();
Field pinCodeField = person.getClass()
.getDeclaredField("pinCode");
pinCodeField.setAccessible(true);
long pinCode = 411057L;
Assertions.assertThrows(IllegalArgumentException.class, () -> pinCodeField.setLong(person, pinCode));
}
@Test
public void whenFieldNotSetAccessible_thenIllegalAccessException() throws Exception {
Person person = new Person();
Field nameField = person.getClass()
.getDeclaredField("name");
Assertions.assertThrows(IllegalAccessException.class, () -> nameField.set(person, "Umang Budhwar"));
}
@Test
public void whenAccessingWrongProperty_thenNoSuchFieldException() throws Exception {
Person person = new Person();
Assertions.assertThrows(NoSuchFieldException.class, () -> person.getClass()
.getDeclaredField("firstName"));
}
@Test
public void whenAccessingNullProperty_thenNullPointerException() throws Exception {
Person person = new Person();
Assertions.assertThrows(NullPointerException.class, () -> person.getClass()
.getDeclaredField(null));
}
}

View File

@ -8,5 +8,4 @@
- [Changing Annotation Parameters At Runtime](http://www.baeldung.com/java-reflection-change-annotation-params)
- [Dynamic Proxies in Java](http://www.baeldung.com/java-dynamic-proxies)
- [What Causes java.lang.reflect.InvocationTargetException?](https://www.baeldung.com/java-lang-reflect-invocationtargetexception)
- [How to Find all Getters Returning Null](http://www.baeldung.com/java-getters-returning-null)
- [How to Get a Name of a Method Being Executed?](http://www.baeldung.com/java-name-of-executing-method)

View File

@ -3,6 +3,7 @@
## Core Java 8 Cookbooks and Examples
### Relevant Articles:
- [An Overview of Regular Expressions Performance in Java](https://www.baeldung.com/java-regex-performance)
- [A Guide To Java Regular Expressions API](http://www.baeldung.com/regular-expressions-java)
- [Guide to Escaping Characters in Java RegExps](http://www.baeldung.com/java-regexp-escape-char)
@ -11,3 +12,4 @@
- [How to Use Regular Expressions to Replace Tokens in Strings](https://www.baeldung.com/java-regex-token-replacement)
- [Regular Expressions \s and \s+ in Java](https://www.baeldung.com/java-regex-s-splus)
- [Validate Phone Numbers With Java Regex](https://www.baeldung.com/java-regex-validate-phone-numbers)
- [How to Count the Number of Matches for a Regex?](https://www.baeldung.com/java-count-regex-matches)

View File

@ -1,12 +1,11 @@
package com.baeldung.regex.countmatches;
import static org.junit.Assert.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.Test;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.junit.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Unit Test intended to count number of matches of a RegEx using Java 8 and 9.
@ -65,7 +64,7 @@ public class CountMatchesUnitTest {
count++;
}
assertNotEquals(3, count);
assertEquals(2, count);
}
@Test

View File

@ -9,4 +9,5 @@ This module contains articles about core Java Security
- [Hashing a Password in Java](https://www.baeldung.com/java-password-hashing)
- [SHA-256 and SHA3-256 Hashing in Java](https://www.baeldung.com/sha-256-hashing-java)
- [Checksums in Java](https://www.baeldung.com/java-checksums)
- [How to Read PEM File to Get Public and Private Keys](https://www.baeldung.com/java-read-pem-file-keys)
- More articles: [[<-- prev]](/core-java-modules/core-java-security)

View File

@ -0,0 +1,3 @@
### Relevant Articles:
- [Version Comparison in Java](https://www.baeldung.com/java-comparing-versions)

View File

@ -1,13 +1,13 @@
## Core Java Cookbooks and Examples
### Relevant Articles:
[Getting Started with Java Properties](http://www.baeldung.com/java-properties)
[Java Money and the Currency API](http://www.baeldung.com/java-money-and-currency)
[Introduction to Java Serialization](http://www.baeldung.com/java-serialization)
[Guide to UUID in Java](http://www.baeldung.com/java-uuid)
[Compiling Java *.class Files with javac](http://www.baeldung.com/javac)
[Introduction to Javadoc](http://www.baeldung.com/javadoc)
[Guide to the Externalizable Interface in Java](http://www.baeldung.com/java-externalizable)
[What is the serialVersionUID?](http://www.baeldung.com/java-serial-version-uid)
[A Guide to the ResourceBundle](http://www.baeldung.com/java-resourcebundle)
[Merging java.util.Properties Objects](https://www.baeldung.com/java-merging-properties)
- [Getting Started with Java Properties](http://www.baeldung.com/java-properties)
- [Java Money and the Currency API](http://www.baeldung.com/java-money-and-currency)
- [Introduction to Java Serialization](http://www.baeldung.com/java-serialization)
- [Guide to UUID in Java](http://www.baeldung.com/java-uuid)
- [Compiling Java *.class Files with javac](http://www.baeldung.com/javac)
- [Introduction to Javadoc](http://www.baeldung.com/javadoc)
- [Guide to the Externalizable Interface in Java](http://www.baeldung.com/java-externalizable)
- [What is the serialVersionUID?](http://www.baeldung.com/java-serial-version-uid)
- [A Guide to the ResourceBundle](http://www.baeldung.com/java-resourcebundle)
- [Merging java.util.Properties Objects](https://www.baeldung.com/java-merging-properties)

View File

@ -22,6 +22,7 @@
<!-- <module>core-java-11</module> --> <!-- We haven't upgraded to java 11. Fixing in BAEL-10841 -->
<!-- <module>core-java-12</module> --> <!-- We haven't upgraded to java 12. Fixing in BAEL-10841 -->
<!-- <module>core-java-13</module> --> <!-- We haven't upgraded to java 12. Fixing in BAEL-10841 -->
<!-- <module>core-java-14</module> --> <!-- We haven't upgraded to java 14.-->
<module>core-java-8</module>
<module>core-java-8-2</module>
@ -59,15 +60,20 @@
<module>core-java-concurrency-basic</module>
<module>core-java-concurrency-basic-2</module>
<module>core-java-concurrency-collections</module>
<module>core-java-concurrency-collections-2</module>
<module>core-java-console</module>
<!--<module>core-java-8-datetime</module>--> <!-- unit test case failure -->
<module>core-java-8-datetime-2</module>
<!-- <module>core-java-date-operations-1</module> --> <!-- We haven't upgraded to java 9. Fixing in BAEL-10841 -->
<module>core-java-date-operations-2</module>
<!-- We haven't upgraded to java 9. -->
<!-- <module>core-java-datetime-computations</module> <module>core-java-datetime-conversion</module> <module>core-java-datetime-java8</module> <module>core-java-datetime-string</module> -->
<module>core-java-8-datetime</module>
<module>core-java-exceptions</module>
<module>core-java-exceptions-2</module>
<module>core-java-exceptions-3</module>
<module>core-java-function</module>
<module>core-java-io</module>

Some files were not shown because too many files have changed in this diff Show More