Merge pull request #3 from eugenp/master

update
This commit is contained in:
marcodenisi 2020-08-28 21:23:18 +02:00 committed by GitHub
commit 8128ce2818
2335 changed files with 38798 additions and 5176 deletions

7
.gitignore vendored
View File

@ -85,7 +85,6 @@ transaction.log
*-shell.log
apache-cxf/cxf-aegis/baeldung.xml
apache-fop/src/test/resources/input.xml
apache-fop/src/test/resources/output_herold.pdf
apache-fop/src/test/resources/output_html2fo.pdf
apache-fop/src/test/resources/output_jtidy.pdf
testing-modules/report-*.json
libraries-2/*.db

View File

@ -1,16 +1,21 @@
package com.baeldung.jgrapht;
import static org.junit.Assert.assertTrue;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import org.jgrapht.ext.JGraphXAdapter;
import org.jgrapht.graph.DefaultDirectedGraph;
import org.jgrapht.graph.DefaultEdge;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.mxgraph.layout.mxCircleLayout;
import com.mxgraph.layout.mxIGraphLayout;
import com.mxgraph.util.mxCellRenderer;
@ -20,7 +25,7 @@ public class GraphImageGenerationUnitTest {
@Before
public void createGraph() throws IOException {
File imgFile = new File("src/test/resources/graph.png");
File imgFile = new File("src/test/resources/graph1.png");
imgFile.createNewFile();
g = new DefaultDirectedGraph<String, DefaultEdge>(DefaultEdge.class);
String x1 = "x1";
@ -34,12 +39,18 @@ public class GraphImageGenerationUnitTest {
g.addEdge(x3, x1);
}
@After
public void cleanup() {
File imgFile = new File("src/test/resources/graph1.png");
imgFile.deleteOnExit();
}
@Test
public void givenAdaptedGraph_whenWriteBufferedImage_ThenFileShouldExist() throws IOException {
JGraphXAdapter<String, DefaultEdge> graphAdapter = new JGraphXAdapter<String, DefaultEdge>(g);
mxIGraphLayout layout = new mxCircleLayout(graphAdapter);
layout.execute(graphAdapter.getDefaultParent());
File imgFile = new File("src/test/resources/graph.png");
File imgFile = new File("src/test/resources/graph1.png");
BufferedImage image = mxCellRenderer.createBufferedImage(graphAdapter, null, 2, Color.WHITE, true, null);
ImageIO.write(image, "PNG", imgFile);
assertTrue(imgFile.exists());

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

@ -1,7 +1,7 @@
package com.baeldung.algorithms.play2048;
public class Play2048 {
private static final int SIZE = 3;
private static final int SIZE = 4;
private static final int INITIAL_NUMBERS = 2;
public static void main(String[] args) {

View File

@ -0,0 +1,26 @@
package com.baeldung.algorithms.topkelements;
import java.util.ArrayList;
import java.util.List;
public class BruteForceTopKElementsFinder implements TopKElementsFinder<Integer> {
public List<Integer> findTopK(List<Integer> input, int k) {
List<Integer> array = new ArrayList<>(input);
List<Integer> topKList = new ArrayList<>();
for (int i = 0; i < k; i++) {
int maxIndex = 0;
for (int j = 1; j < array.size(); j++) {
if (array.get(j) > array.get(maxIndex)) {
maxIndex = j;
}
}
topKList.add(array.remove(maxIndex));
}
return topKList;
}
}

View File

@ -0,0 +1,26 @@
package com.baeldung.algorithms.topkelements;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.PriorityQueue;
public class MaxHeapTopKElementsFinder implements TopKElementsFinder<Integer> {
public List<Integer> findTopK(List<Integer> input, int k) {
PriorityQueue<Integer> maxHeap = new PriorityQueue<>();
input.forEach(number -> {
maxHeap.add(number);
if (maxHeap.size() > k) {
maxHeap.poll();
}
});
List<Integer> topKList = new ArrayList<>(maxHeap);
Collections.reverse(topKList);
return topKList;
}
}

View File

@ -0,0 +1,7 @@
package com.baeldung.algorithms.topkelements;
import java.util.List;
public interface TopKElementsFinder<T extends Comparable<T>> {
List<T> findTopK(List<T> input, int k);
}

View File

@ -0,0 +1,17 @@
package com.baeldung.algorithms.topkelements;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.stream.Collectors;
public class TreeSetTopKElementsFinder implements TopKElementsFinder<Integer> {
public List<Integer> findTopK(List<Integer> input, int k) {
Set<Integer> sortedSet = new TreeSet<>(Comparator.reverseOrder());
sortedSet.addAll(input);
return sortedSet.stream().limit(k).collect(Collectors.toList());
}
}

View File

@ -0,0 +1,46 @@
package com.baeldung.algorithms.topkelements;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import static org.assertj.core.api.Java6Assertions.assertThat;
public class TopKElementsFinderUnitTest {
private final TopKElementsFinder<Integer> bruteForceFinder = new BruteForceTopKElementsFinder();
private final TopKElementsFinder<Integer> maxHeapFinder = new MaxHeapTopKElementsFinder();
private final TopKElementsFinder<Integer> treeSetFinder = new TreeSetTopKElementsFinder();
private final int k = 4;
private final List<Integer> distinctIntegers = Arrays.asList(1, 2, 3, 9, 7, 6, 12);
private final List<Integer> distinctIntegersTopK = Arrays.asList(9, 7, 6, 12);
private final List<Integer> nonDistinctIntegers = Arrays.asList(1, 2, 3, 3, 9, 9, 7, 6, 12);
private final List<Integer> nonDistinctIntegersTopK = Arrays.asList(9, 9, 7, 12);
@Test
public void givenArrayDistinctIntegers_whenBruteForceFindTopK_thenReturnKLargest() {
assertThat(bruteForceFinder.findTopK(distinctIntegers, k)).containsOnlyElementsOf(distinctIntegersTopK);
}
@Test
public void givenArrayDistinctIntegers_whenMaxHeapFindTopK_thenReturnKLargest() {
assertThat(maxHeapFinder.findTopK(distinctIntegers, k)).containsOnlyElementsOf(distinctIntegersTopK);
}
@Test
public void givenArrayDistinctIntegers_whenTreeSetFindTopK_thenReturnKLargest() {
assertThat(treeSetFinder.findTopK(distinctIntegers, k)).containsOnlyElementsOf(distinctIntegersTopK);
}
@Test
public void givenArrayNonDistinctIntegers_whenBruteForceFindTopK_thenReturnKLargest() {
assertThat(bruteForceFinder.findTopK(nonDistinctIntegers, k)).containsOnlyElementsOf(nonDistinctIntegersTopK);
}
@Test
public void givenArrayNonDistinctIntegers_whenMaxHeapFindTopK_thenReturnKLargest() {
assertThat(maxHeapFinder.findTopK(nonDistinctIntegers, k)).containsOnlyElementsOf(nonDistinctIntegersTopK);
}
}

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

@ -2,7 +2,7 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>apache-miscellaneous-1</artifactId>
<artifactId>apache-libraries</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>apache-libraries</name>

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

@ -39,10 +39,19 @@
<artifactId>jcl-over-slf4j</artifactId>
<scope>runtime</scope>
</dependency>
<!-- spring-sec -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
</dependencies>
<properties>
<apache-shiro-core-version>1.4.0</apache-shiro-core-version>
<apache-shiro-core-version>1.5.3</apache-shiro-core-version>
<log4j-version>1.2.17</log4j-version>
</properties>

View File

@ -0,0 +1,96 @@
package com.baeldung.comparison.shiro;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.jdbc.JdbcRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class CustomRealm extends JdbcRealm {
private Logger logger = LoggerFactory.getLogger(CustomRealm.class);
private Map<String, String> credentials = new HashMap<>();
private Map<String, Set<String>> roles = new HashMap<>();
private Map<String, Set<String>> permissions = new HashMap<>();
{
credentials.put("Tom", "password");
credentials.put("Jerry", "password");
roles.put("Jerry", new HashSet<>(Arrays.asList("ADMIN")));
roles.put("Tom", new HashSet<>(Arrays.asList("USER")));
permissions.put("ADMIN", new HashSet<>(Arrays.asList("READ", "WRITE")));
permissions.put("USER", new HashSet<>(Arrays.asList("READ")));
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
UsernamePasswordToken userToken = (UsernamePasswordToken) token;
if (userToken.getUsername() == null || userToken.getUsername()
.isEmpty() || !credentials.containsKey(userToken.getUsername())) {
throw new UnknownAccountException("User doesn't exist");
}
return new SimpleAuthenticationInfo(userToken.getUsername(), credentials.get(userToken.getUsername()), getName());
}
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
Set<String> roles = new HashSet<>();
Set<String> permissions = new HashSet<>();
for (Object user : principals) {
try {
roles.addAll(getRoleNamesForUser(null, (String) user));
permissions.addAll(getPermissions(null, null, roles));
} catch (SQLException e) {
logger.error(e.getMessage());
}
}
SimpleAuthorizationInfo authInfo = new SimpleAuthorizationInfo(roles);
authInfo.setStringPermissions(permissions);
return authInfo;
}
@Override
protected Set<String> getRoleNamesForUser(Connection conn, String username) throws SQLException {
if (!roles.containsKey(username)) {
throw new SQLException("User doesn't exist");
}
return roles.get(username);
}
@Override
protected Set<String> getPermissions(Connection conn, String username, Collection<String> roles) throws SQLException {
Set<String> userPermissions = new HashSet<>();
for (String role : roles) {
if (!permissions.containsKey(role)) {
throw new SQLException("Role doesn't exist");
}
userPermissions.addAll(permissions.get(role));
}
return userPermissions;
}
}

View File

@ -0,0 +1,33 @@
package com.baeldung.comparison.shiro;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition;
import org.apache.shiro.spring.web.config.ShiroFilterChainDefinition;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
import org.springframework.context.annotation.Bean;
@SpringBootApplication(exclude = SecurityAutoConfiguration.class)
public class ShiroApplication {
public static void main(String... args) {
SpringApplication.run(ShiroApplication.class, args);
}
@Bean
public Realm customRealm() {
return new CustomRealm();
}
@Bean
public ShiroFilterChainDefinition shiroFilterChainDefinition() {
DefaultShiroFilterChainDefinition filter = new DefaultShiroFilterChainDefinition();
filter.addPathDefinition("/home", "authc");
filter.addPathDefinition("/**", "anon");
return filter;
}
}

View File

@ -0,0 +1,99 @@
package com.baeldung.comparison.shiro.controllers;
import javax.servlet.http.HttpServletRequest;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.baeldung.comparison.shiro.models.UserCredentials;
@Controller
public class ShiroController {
private Logger logger = LoggerFactory.getLogger(ShiroController.class);
@GetMapping("/")
public String getIndex() {
return "comparison/index";
}
@GetMapping("/login")
public String showLoginPage() {
return "comparison/login";
}
@PostMapping("/login")
public String doLogin(HttpServletRequest req, UserCredentials credentials, RedirectAttributes attr) {
Subject subject = SecurityUtils.getSubject();
if (!subject.isAuthenticated()) {
UsernamePasswordToken token = new UsernamePasswordToken(credentials.getUsername(), credentials.getPassword());
try {
subject.login(token);
} catch (AuthenticationException ae) {
logger.error(ae.getMessage());
attr.addFlashAttribute("error", "Invalid Credentials");
return "redirect:/login";
}
}
return "redirect:/home";
}
@GetMapping("/home")
public String getMeHome(Model model) {
addUserAttributes(model);
return "comparison/home";
}
@GetMapping("/admin")
public String adminOnly(Model model) {
addUserAttributes(model);
Subject currentUser = SecurityUtils.getSubject();
if (currentUser.hasRole("ADMIN")) {
model.addAttribute("adminContent", "only admin can view this");
}
return "comparison/home";
}
@PostMapping("/logout")
public String logout() {
Subject subject = SecurityUtils.getSubject();
subject.logout();
return "redirect:/";
}
private void addUserAttributes(Model model) {
Subject currentUser = SecurityUtils.getSubject();
String permission = "";
if (currentUser.hasRole("ADMIN")) {
model.addAttribute("role", "ADMIN");
} else if (currentUser.hasRole("USER")) {
model.addAttribute("role", "USER");
}
if (currentUser.isPermitted("READ")) {
permission = permission + " READ";
}
if (currentUser.isPermitted("WRITE")) {
permission = permission + " WRITE";
}
model.addAttribute("username", currentUser.getPrincipal());
model.addAttribute("permission", permission);
}
}

View File

@ -0,0 +1,28 @@
package com.baeldung.comparison.shiro.models;
public class UserCredentials {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "username = " + getUsername();
}
}

View File

@ -0,0 +1,19 @@
package com.baeldung.comparison.springsecurity;
import org.apache.shiro.spring.boot.autoconfigure.ShiroAnnotationProcessorAutoConfiguration;
import org.apache.shiro.spring.boot.autoconfigure.ShiroAutoConfiguration;
import org.apache.shiro.spring.config.web.autoconfigure.ShiroWebAutoConfiguration;
import org.apache.shiro.spring.config.web.autoconfigure.ShiroWebFilterConfiguration;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication(exclude = {ShiroAutoConfiguration.class,
ShiroAnnotationProcessorAutoConfiguration.class,
ShiroWebAutoConfiguration.class,
ShiroWebFilterConfiguration.class})
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}

View File

@ -0,0 +1,45 @@
package com.baeldung.comparison.springsecurity.config;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests(authorize -> authorize.antMatchers("/index", "/login")
.permitAll()
.antMatchers("/home", "/logout")
.authenticated()
.antMatchers("/admin/**")
.hasRole("ADMIN"))
.formLogin(formLogin -> formLogin.loginPage("/login")
.failureUrl("/login-error"));
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("Jerry")
.password(passwordEncoder().encode("password"))
.authorities("READ", "WRITE")
.roles("ADMIN")
.and()
.withUser("Tom")
.password(passwordEncoder().encode("password"))
.authorities("READ")
.roles("USER");
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}

View File

@ -0,0 +1,79 @@
package com.baeldung.comparison.springsecurity.web;
import java.util.Collection;
import javax.servlet.http.HttpServletRequest;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class SpringController {
@GetMapping("/")
public String getIndex() {
return "comparison/index";
}
@GetMapping("/login")
public String showLoginPage() {
return "comparison/login";
}
@RequestMapping("/login-error")
public String loginError(Model model) {
model.addAttribute("error", "Invalid Credentials");
return "comparison/login";
}
@PostMapping("/login")
public String doLogin(HttpServletRequest req) {
return "redirect:/home";
}
@GetMapping("/home")
public String showHomePage(HttpServletRequest req, Model model) {
addUserAttributes(model);
return "comparison/home";
}
@GetMapping("/admin")
public String adminOnly(HttpServletRequest req, Model model) {
addUserAttributes(model);
model.addAttribute("adminContent", "only admin can view this");
return "comparison/home";
}
private void addUserAttributes(Model model) {
Authentication auth = SecurityContextHolder.getContext()
.getAuthentication();
if (auth != null && !auth.getClass()
.equals(AnonymousAuthenticationToken.class)) {
User user = (User) auth.getPrincipal();
model.addAttribute("username", user.getUsername());
Collection<GrantedAuthority> authorities = user.getAuthorities();
for (GrantedAuthority authority : authorities) {
if (authority.getAuthority()
.contains("USER")) {
model.addAttribute("role", "USER");
model.addAttribute("permission", "READ");
} else if (authority.getAuthority()
.contains("ADMIN")) {
model.addAttribute("role", "ADMIN");
model.addAttribute("permission", "READ WRITE");
}
}
}
}
}

View File

@ -1,4 +1,4 @@
package com.baeldung;
package com.baeldung.intro;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;

View File

@ -1,4 +1,4 @@
package com.baeldung;
package com.baeldung.intro;
import java.sql.Connection;
import java.sql.SQLException;

View File

@ -1,4 +1,4 @@
package com.baeldung;
package com.baeldung.intro;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition;
@ -7,12 +7,13 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
import org.springframework.context.annotation.Bean;
/**
* Created by smatt on 21/08/2017.
*/
@SpringBootApplication
@SpringBootApplication(exclude = SecurityAutoConfiguration.class)
public class ShiroSpringApplication {
private static final transient Logger log = LoggerFactory.getLogger(ShiroSpringApplication.class);
@ -29,7 +30,7 @@ public class ShiroSpringApplication {
@Bean
public ShiroFilterChainDefinition shiroFilterChainDefinition() {
public ShiroFilterChainDefinition filterChainDefinition() {
DefaultShiroFilterChainDefinition filter
= new DefaultShiroFilterChainDefinition();

View File

@ -1,6 +1,5 @@
package com.baeldung.controllers;
package com.baeldung.intro.controllers;
import com.baeldung.models.UserCredentials;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
@ -13,6 +12,8 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.baeldung.intro.models.UserCredentials;
import javax.servlet.http.HttpServletRequest;
@Controller

View File

@ -1,4 +1,4 @@
package com.baeldung.models;
package com.baeldung.intro.models;
public class UserCredentials {

View File

@ -1,4 +1,4 @@
package com.baeldung.shiro.permissions.custom;
package com.baeldung.permissions.custom;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;

View File

@ -1,4 +1,4 @@
package com.baeldung.shiro.permissions.custom;
package com.baeldung.permissions.custom;
import org.apache.shiro.authz.Permission;

View File

@ -1,4 +1,4 @@
package com.baeldung.shiro.permissions.custom;
package com.baeldung.permissions.custom;
import org.apache.shiro.authz.Permission;
import org.apache.shiro.authz.permission.PermissionResolver;

View File

@ -0,0 +1,19 @@
<html>
<head>
<title>Home Page</title>
</head>
<body style="margin-left: 30px;">
<h1>Welcome ${username}!</h1>
<p><strong>Role</strong>: ${role}</p>
<p><strong>Permissions</strong></p>
<p>${permission}</p>
<a href="/admin">Admin only</a>
<#if adminContent??>
${adminContent}
</#if>
<br>
<form role="form" action="/logout" method="POST">
<input type="Submit" value="Logout" />
</form>
</body>
</html>

View File

@ -0,0 +1,10 @@
<html>
<head>
<title>Index</title>
</head>
<body>
<h1>Welcome Guest!</h1>
<br>
Go to the <a href="/home">secured page
</body>
</html>

View File

@ -0,0 +1,25 @@
<html>
<head>
<title>Login</title>
</head>
<body style="margin-left: 30px;">
<h3>Login</h3>
<br>
<form action="/login" method="post">
<#if (error?length > 0)??>
<p style="color:darkred;">${error}</p>
<#else>
</#if>
<label for="username">Username</label>
<br>
<input type="text" name="username">
<br><br>
<label for="password">Password</label>
<br>
<input type="password" name="password">
<br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>

View File

@ -0,0 +1,20 @@
package com.baeldung.comparison.shiro;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import com.baeldung.comparison.shiro.ShiroApplication;
@ExtendWith(SpringExtension.class)
@SpringBootTest(classes = { ShiroApplication.class })
public class SpringContextTest {
@Test
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
}
}

View File

@ -0,0 +1,19 @@
package com.baeldung.comparison.springsecurity;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import com.baeldung.comparison.springsecurity.Application;
@ExtendWith(SpringExtension.class)
@SpringBootTest(classes = { Application.class })
public class SpringContextTest {
@Test
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
}
}

View File

@ -2,23 +2,16 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.baeldung</groupId>
<artifactId>aws-app-sync</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>aws-app-sync</name>
<description>Spring Boot using AWS App Sync</description>
<properties>
<java.version>1.8</java.version>
</properties>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-boot-2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-boot-2</relativePath>
</parent>
<dependencies>

View File

@ -12,7 +12,7 @@ import static org.junit.jupiter.api.Assertions.*;
@SpringBootTest
@Disabled
class AwsAppSyncApplicationTests {
class AwsAppSyncApplicationUnitTest {
@Test
void givenGraphQuery_whenListEvents_thenReturnAllEvents() {

View File

@ -1,8 +1,8 @@
<?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>cdi</artifactId>
<version>1.0-SNAPSHOT</version>
@ -10,9 +10,9 @@
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-spring-4</artifactId>
<artifactId>parent-spring-5</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-spring-4</relativePath>
<relativePath>../parent-spring-5</relativePath>
</parent>
<dependencies>
@ -26,28 +26,22 @@
<artifactId>weld-se-core</artifactId>
<version>${weld-se-core.version}</version>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest</artifactId>
<version>${hamcrest.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj-core.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>${aspectjweaver.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
@ -61,7 +55,6 @@
<weld-se-core.version>3.0.5.Final</weld-se-core.version>
<aspectjweaver.version>1.9.2</aspectjweaver.version>
<assertj-core.version>3.10.0</assertj-core.version>
<spring.version>5.1.2.RELEASE</spring.version>
</properties>
</project>

View File

@ -6,7 +6,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>cf-uaa-oauth2-client</artifactId>
<name>uaa-client-webapp</name>
<name>cf-uaa-oauth2-client</name>
<description>Demo project for Spring Boot</description>
<parent>

View File

@ -1,44 +0,0 @@
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung.groovy</groupId>
<artifactId>determine-datatype</artifactId>
<version>0.0.1-SNAPSHOT</version>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.gmaven</groupId>
<artifactId>groovy-maven-plugin</artifactId>
<dependencies>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
<version>2.0.6</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.junit/junit5-engine -->
<dependency>
<groupId>org.junit</groupId>
<artifactId>junit5-engine</artifactId>
<version>${junit5.version}</version>
</dependency>
</dependencies>
<properties>
<junit5.version>5.0.0-ALPHA</junit5.version>
</properties>
</project>

View File

@ -1,14 +0,0 @@
package com.baeldung.groovy.determine.datatype
class Person {
private int ageAsInt
private Double ageAsDouble
private String ageAsString
Person() {}
Person(int ageAsInt) { this.ageAsInt = ageAsInt}
Person(Double ageAsDouble) { this.ageAsDouble = ageAsDouble}
Person(String ageAsString) { this.ageAsString = ageAsString}
}
class Student extends Person {}

View File

@ -1,55 +0,0 @@
package com.baeldung.groovy.determine.datatype;
import org.junit.Assert
import org.junit.Test;
public class PersonTest {
@Test
public void givenWhenParameterTypeIsInteger_thenReturnTrue() {
Person personObj = new Person(10)
Assert.assertTrue(personObj.ageAsInt instanceof Integer);
}
@Test
public void givenWhenParameterTypeIsDouble_thenReturnTrue() {
Person personObj = new Person(10.0)
Assert.assertTrue((personObj.ageAsDouble).getClass() == Double)
}
@Test
public void givenWhenParameterTypeIsString_thenReturnTrue() {
Person personObj = new Person("10 years")
Assert.assertTrue(personObj.ageAsString.class == String)
}
@Test
public void givenClassName_WhenParameterIsInteger_thenReturnTrue() {
Assert.assertTrue(Person.class.getDeclaredField('ageAsInt').type == int.class)
}
@Test
public void givenWhenObjectIsInstanceOfType_thenReturnTrue() {
Person personObj = new Person()
Assert.assertTrue(personObj instanceof Person)
}
@Test
public void givenWhenInstanceIsOfSubtype_thenReturnTrue() {
Student studentObj = new Student()
Assert.assertTrue(studentObj in Person)
}
@Test
public void givenGroovyList_WhenFindClassName_thenReturnTrue() {
def ageList = ['ageAsString','ageAsDouble', 10]
Assert.assertTrue(ageList.class == ArrayList)
Assert.assertTrue(ageList.getClass() == ArrayList)
}
@Test
public void givenGrooyMap_WhenFindClassName_thenReturnTrue() {
def ageMap = [ageAsString: '10 years', ageAsDouble: 10.0]
Assert.assertFalse(ageMap.class == LinkedHashMap)
}
}

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

@ -10,5 +10,6 @@ public class CopyListServiceUnitTest {
@Test(expected = UnsupportedOperationException.class)
public void whenModifyCopyOfList_thenThrowsException() {
List<Integer> copyList = List.copyOf(Arrays.asList(1, 2, 3, 4));
copyList.add(4);
}
}

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

@ -6,7 +6,7 @@
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-8-datetime-2</artifactId>
<version>${project.parent.version}</version>
<name>core-java-8-datetime</name>
<name>core-java-8-datetime-2</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>

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

@ -1,12 +1,15 @@
package com.baeldung.modules.main;
import com.baeldung.modules.hello.HelloInterface;
import com.baeldung.modules.hello.HelloModules;
import java.util.ServiceLoader;
public class MainApp {
public static void main(String[] args) {
HelloModules.doSomething();
HelloModules module = new HelloModules();
module.sayHello();
Iterable<HelloInterface> services = ServiceLoader.load(HelloInterface.class);
HelloInterface service = services.iterator().next();
service.sayHello();
}
}

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

@ -0,0 +1,23 @@
package com.baeldung.java9.currentmethod;
import org.junit.Test;
import java.util.Optional;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class CurrentExecutingMethodUnitTest {
@Test
public void givenJava9_whenWalkingTheStack_thenFindMethod() {
StackWalker walker = StackWalker.getInstance();
Optional<String> methodName = walker.walk(frames -> frames
.findFirst()
.map(StackWalker.StackFrame::getMethodName)
);
assertTrue(methodName.isPresent());
assertEquals("givenJava9_whenWalkingTheStack_thenFindMethod", methodName.get());
}
}

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

@ -13,32 +13,6 @@
<name>core-java-arrays-operations-basic</name>
<packaging>jar</packaging>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>${shade.plugin.version}</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<finalName>benchmarks</finalName>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>org.openjdk.jmh.Main</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
@ -66,6 +40,32 @@
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>${shade.plugin.version}</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<finalName>benchmarks</finalName>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>org.openjdk.jmh.Main</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<properties>
<shade.plugin.version>3.2.0</shade.plugin.version>

View File

@ -14,32 +14,6 @@
<name>core-java-arrays-sorting</name>
<packaging>jar</packaging>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>${shade.plugin.version}</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<finalName>benchmarks</finalName>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>org.openjdk.jmh.Main</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>
<!-- Utilities -->
<dependency>
@ -74,6 +48,32 @@
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>${shade.plugin.version}</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<finalName>benchmarks</finalName>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>org.openjdk.jmh.Main</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<properties>
<shade.plugin.version>3.2.0</shade.plugin.version>

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>
@ -27,11 +32,17 @@
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.10</version>
</dependency>
</dependencies>
<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,47 @@
package com.baeldung.collections.iterators;
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import com.google.common.primitives.Ints;
import org.apache.commons.lang3.ArrayUtils;
public class ConvertPrimitivesArrayToList {
public static void failConvert() {
int[] input = new int[]{1,2,3,4};
// List<Integer> inputAsList = Arrays.asList(input);
}
public static List<Integer> iterateConvert(int[] input) {
List<Integer> output = new ArrayList<Integer>();
for (int value : input) {
output.add(value);
}
return output;
}
public static List<Integer> streamConvert(int[] input) {
List<Integer> output = Arrays.stream(input).boxed().collect(Collectors.toList());
return output;
}
public static List<Integer> streamConvertIntStream(int[] input) {
List<Integer> output = IntStream.of(input).boxed().collect(Collectors.toList());
return output;
}
public static List<Integer> guavaConvert(int[] input) {
List<Integer> output = Ints.asList(input);
return output;
}
public static List<Integer> apacheCommonConvert(int[] input) {
Integer[] outputBoxed = ArrayUtils.toObject(input);
List<Integer> output = Arrays.asList(outputBoxed);
return output;
}
}

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

@ -0,0 +1,38 @@
package com.baeldung.collections.iterators;
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.stream.Collectors;
import com.google.common.primitives.Ints;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class ConvertPrimitivesArrayToListUnitTest {
@Test
public void givenArrayWithPrimitives_whenIterativeConvert_thenArrayGetsConverted() {
assertEquals(Arrays.asList(1,2,3,4), ConvertPrimitivesArrayToList.iterateConvert(new int[]{1,2,3,4}));
}
@Test
public void givenArrayWithPrimitives_whenStreamConvert_thenArrayGetsConverted() {
assertEquals(Arrays.asList(1,2,3,4), ConvertPrimitivesArrayToList.streamConvert(new int[]{1,2,3,4}));
}
@Test
public void givenArrayWithPrimitives_whenIntStreamConvert_thenArrayGetsConverted() {
assertEquals(Arrays.asList(1,2,3,4), ConvertPrimitivesArrayToList.streamConvertIntStream(new int[]{1,2,3,4}));
}
@Test
public void givenArrayWithPrimitives_whenGuavaConvert_thenArrayGetsConverted() {
assertEquals(Arrays.asList(1,2,3,4), ConvertPrimitivesArrayToList.guavaConvert(new int[]{1,2,3,4}));
}
@Test
public void givenArrayWithPrimitives_whenApacheCommonConvert_thenArrayGetsConverted() {
assertEquals(Arrays.asList(1,2,3,4), ConvertPrimitivesArrayToList.apacheCommonConvert(new int[]{1,2,3,4}));
}
}

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

@ -0,0 +1,10 @@
package com.baeldung.concurrent.localvariables;
public class LocalAndLambda {
public static void main(String... args) {
String text = "";
// Un-commenting the next line will break compilation, because text is no longer effectively final
// text = "675";
new Thread(() -> System.out.println(text)).start();
}
}

View File

@ -0,0 +1,20 @@
package com.baeldung.concurrent.localvariables;
import java.security.SecureRandom;
public class LocalVariables implements Runnable {
private int field;
public static void main(String... args) {
LocalVariables target = new LocalVariables();
new Thread(target).start();
new Thread(target).start();
}
@Override
public void run() {
field = new SecureRandom().nextInt();
int local = new SecureRandom().nextInt();
System.out.println(field + " - " + local);
}
}

View File

@ -1,3 +1,5 @@
### Relevant Articles:
- [Introduction to Lock Striping](https://www.baeldung.com/java-lock-stripping)
- [Guide to the Java TransferQueue](http://www.baeldung.com/java-transfer-queue)
- [[<-- Prev]](/core-java-modules/core-java-concurrency-collections)

View File

@ -3,9 +3,16 @@
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.concurrent.lock</groupId>
<artifactId>core-java-concurrency-collections-2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-concurrency-collections-2</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>
<dependency>
@ -30,19 +37,6 @@
<scope>test</scope>
</dependency>
</dependencies>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<jmh.version>1.21</jmh.version>

View File

@ -19,7 +19,7 @@ import org.junit.FixMethodOrder;
import org.junit.Test;
@FixMethodOrder
public class TestConcurrentLinkedQueue {
public class ConcurrentLinkedQueueUnitTest {
@Test
public void givenThereIsExistingCollection_WhenAddedIntoQueue_ThenShouldContainElements() {

View File

@ -18,7 +18,7 @@ import org.junit.FixMethodOrder;
import org.junit.Test;
@FixMethodOrder
public class TestLinkedBlockingQueue {
public class LinkedBlockingQueueUnitTest {
@Test
public void givenThereIsExistingCollection_WhenAddedIntoQueue_ThenShouldContainElements() {

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