Merge branch 'master' into thombergs-patch-7
This commit is contained in:
@@ -62,3 +62,5 @@ jmeter/src/main/resources/*-JMeter.csv
|
||||
**/dist
|
||||
**/tmp
|
||||
**/out-tsc
|
||||
**/nbproject/
|
||||
**/nb-configuration.xml
|
||||
+1
-1
@@ -4,7 +4,7 @@ before_install:
|
||||
- echo "MAVEN_OPTS='-Xmx2048M -Xss128M -XX:+CMSClassUnloadingEnabled -XX:+UseG1GC -XX:-UseGCOverheadLimit'" > ~/.mavenrc
|
||||
|
||||
install: skip
|
||||
script: travis_wait 60 mvn -q install -Pdefault
|
||||
script: travis_wait 60 mvn -q install -Pdefault-first,default-second
|
||||
|
||||
sudo: required
|
||||
|
||||
|
||||
@@ -21,3 +21,8 @@ In additional to Spring, the following technologies are in focus: `core Java`, `
|
||||
Building the project
|
||||
====================
|
||||
To do the full build, do: `mvn install -Pdefault -Dgib.enabled=false`
|
||||
|
||||
|
||||
Building a single module
|
||||
====================
|
||||
To build a specific module run the command: `mvn clean install -Dgib.enabled=false` in the module directory
|
||||
|
||||
@@ -28,3 +28,6 @@
|
||||
- [Calculate the Distance Between Two Points in Java](https://www.baeldung.com/java-distance-between-two-points)
|
||||
- [Find the Intersection of Two Lines in Java](https://www.baeldung.com/java-intersection-of-two-lines)
|
||||
- [Check If a String Contains All The Letters of The Alphabet](https://www.baeldung.com/java-string-contains-all-letters)
|
||||
- [Round Up to the Nearest Hundred](https://www.baeldung.com/java-round-up-nearest-hundred)
|
||||
- [Merge Sort in Java](https://www.baeldung.com/java-merge-sort)
|
||||
- [Calculate Percentage in Java](https://www.baeldung.com/java-calculate-percentage)
|
||||
|
||||
@@ -17,6 +17,11 @@
|
||||
<artifactId>commons-math3</artifactId>
|
||||
<version>${commons-math3.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>commons-codec</groupId>
|
||||
<artifactId>commons-codec</artifactId>
|
||||
<version>${commons-codec.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
@@ -85,6 +90,7 @@
|
||||
<io.jenetics.version>3.7.0</io.jenetics.version>
|
||||
<org.jgrapht.core.version>1.0.1</org.jgrapht.core.version>
|
||||
<org.assertj.core.version>3.9.0</org.assertj.core.version>
|
||||
<commons-codec.version>1.11</commons-codec.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,110 @@
|
||||
package com.baeldung.algorithms.conversion;
|
||||
|
||||
import java.math.BigInteger;
|
||||
|
||||
import javax.xml.bind.DatatypeConverter;
|
||||
|
||||
import org.apache.commons.codec.DecoderException;
|
||||
import org.apache.commons.codec.binary.Hex;
|
||||
|
||||
import com.google.common.io.BaseEncoding;
|
||||
|
||||
public class HexStringConverter {
|
||||
|
||||
/**
|
||||
* Create a byte Array from String of hexadecimal digits using Character conversion
|
||||
* @param hexString - Hexadecimal digits as String
|
||||
* @return Desired byte Array
|
||||
*/
|
||||
public byte[] decodeHexString(String hexString) {
|
||||
if (hexString.length() % 2 == 1) {
|
||||
throw new IllegalArgumentException("Invalid hexadecimal String supplied.");
|
||||
}
|
||||
byte[] bytes = new byte[hexString.length() / 2];
|
||||
|
||||
for (int i = 0; i < hexString.length(); i += 2) {
|
||||
bytes[i / 2] = hexToByte(hexString.substring(i, i + 2));
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a String of hexadecimal digits from a byte Array using Character conversion
|
||||
* @param byteArray - The byte Array
|
||||
* @return Desired String of hexadecimal digits in lower case
|
||||
*/
|
||||
public String encodeHexString(byte[] byteArray) {
|
||||
StringBuffer hexStringBuffer = new StringBuffer();
|
||||
for (int i = 0; i < byteArray.length; i++) {
|
||||
hexStringBuffer.append(byteToHex(byteArray[i]));
|
||||
}
|
||||
return hexStringBuffer.toString();
|
||||
}
|
||||
|
||||
public String byteToHex(byte num) {
|
||||
char[] hexDigits = new char[2];
|
||||
hexDigits[0] = Character.forDigit((num >> 4) & 0xF, 16);
|
||||
hexDigits[1] = Character.forDigit((num & 0xF), 16);
|
||||
return new String(hexDigits);
|
||||
}
|
||||
|
||||
public byte hexToByte(String hexString) {
|
||||
int firstDigit = toDigit(hexString.charAt(0));
|
||||
int secondDigit = toDigit(hexString.charAt(1));
|
||||
return (byte) ((firstDigit << 4) + secondDigit);
|
||||
}
|
||||
|
||||
private int toDigit(char hexChar) {
|
||||
int digit = Character.digit(hexChar, 16);
|
||||
if(digit == -1) {
|
||||
throw new IllegalArgumentException("Invalid Hexadecimal Character: "+ hexChar);
|
||||
}
|
||||
return digit;
|
||||
}
|
||||
|
||||
public String encodeUsingBigIntegerToString(byte[] bytes) {
|
||||
BigInteger bigInteger = new BigInteger(1, bytes);
|
||||
return bigInteger.toString(16);
|
||||
}
|
||||
|
||||
public String encodeUsingBigIntegerStringFormat(byte[] bytes) {
|
||||
BigInteger bigInteger = new BigInteger(1, bytes);
|
||||
return String.format("%0" + (bytes.length << 1) + "x", bigInteger);
|
||||
}
|
||||
|
||||
public byte[] decodeUsingBigInteger(String hexString) {
|
||||
byte[] byteArray = new BigInteger(hexString, 16).toByteArray();
|
||||
if (byteArray[0] == 0) {
|
||||
byte[] output = new byte[byteArray.length - 1];
|
||||
System.arraycopy(byteArray, 1, output, 0, output.length);
|
||||
return output;
|
||||
}
|
||||
return byteArray;
|
||||
}
|
||||
|
||||
public String encodeUsingDataTypeConverter(byte[] bytes) {
|
||||
return DatatypeConverter.printHexBinary(bytes);
|
||||
}
|
||||
|
||||
public byte[] decodeUsingDataTypeConverter(String hexString) {
|
||||
return DatatypeConverter.parseHexBinary(hexString);
|
||||
}
|
||||
|
||||
public String encodeUsingApacheCommons(byte[] bytes) throws DecoderException {
|
||||
return Hex.encodeHexString(bytes);
|
||||
}
|
||||
|
||||
public byte[] decodeUsingApacheCommons(String hexString) throws DecoderException {
|
||||
return Hex.decodeHex(hexString);
|
||||
}
|
||||
|
||||
public String encodeUsingGuava(byte[] bytes) {
|
||||
return BaseEncoding.base16()
|
||||
.encode(bytes);
|
||||
}
|
||||
|
||||
public byte[] decodeUsingGuava(String hexString) {
|
||||
return BaseEncoding.base16()
|
||||
.decode(hexString.toUpperCase());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
package com.baeldung.algorithms.heapsort;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
public class Heap<E extends Comparable<E>> {
|
||||
|
||||
private List<E> elements = new ArrayList<>();
|
||||
|
||||
public static <E extends Comparable<E>> List<E> sort(Iterable<E> elements) {
|
||||
Heap<E> heap = of(elements);
|
||||
|
||||
List<E> result = new ArrayList<>();
|
||||
|
||||
while (!heap.isEmpty()) {
|
||||
result.add(heap.pop());
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public static <E extends Comparable<E>> Heap<E> of(E... elements) {
|
||||
return of(Arrays.asList(elements));
|
||||
}
|
||||
|
||||
public static <E extends Comparable<E>> Heap<E> of(Iterable<E> elements) {
|
||||
Heap<E> result = new Heap<>();
|
||||
for (E element : elements) {
|
||||
result.add(element);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public void add(E e) {
|
||||
elements.add(e);
|
||||
int elementIndex = elements.size() - 1;
|
||||
while (!isRoot(elementIndex) && !isCorrectChild(elementIndex)) {
|
||||
int parentIndex = parentIndex(elementIndex);
|
||||
swap(elementIndex, parentIndex);
|
||||
elementIndex = parentIndex;
|
||||
}
|
||||
}
|
||||
|
||||
public E pop() {
|
||||
if (isEmpty()) {
|
||||
throw new IllegalStateException("You cannot pop from an empty heap");
|
||||
}
|
||||
|
||||
E result = elementAt(0);
|
||||
|
||||
int lasElementIndex = elements.size() - 1;
|
||||
swap(0, lasElementIndex);
|
||||
elements.remove(lasElementIndex);
|
||||
|
||||
int elementIndex = 0;
|
||||
while (!isLeaf(elementIndex) && !isCorrectParent(elementIndex)) {
|
||||
int smallerChildIndex = smallerChildIndex(elementIndex);
|
||||
swap(elementIndex, smallerChildIndex);
|
||||
elementIndex = smallerChildIndex;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public boolean isEmpty() {
|
||||
return elements.isEmpty();
|
||||
}
|
||||
|
||||
private boolean isRoot(int index) {
|
||||
return index == 0;
|
||||
}
|
||||
|
||||
private int smallerChildIndex(int index) {
|
||||
int leftChildIndex = leftChildIndex(index);
|
||||
int rightChildIndex = rightChildIndex(index);
|
||||
|
||||
if (!isValidIndex(rightChildIndex)) {
|
||||
return leftChildIndex;
|
||||
}
|
||||
|
||||
if (elementAt(leftChildIndex).compareTo(elementAt(rightChildIndex)) < 0) {
|
||||
return leftChildIndex;
|
||||
}
|
||||
|
||||
return rightChildIndex;
|
||||
}
|
||||
|
||||
private boolean isLeaf(int index) {
|
||||
return !isValidIndex(leftChildIndex(index));
|
||||
}
|
||||
|
||||
private boolean isCorrectParent(int index) {
|
||||
return isCorrect(index, leftChildIndex(index)) && isCorrect(index, rightChildIndex(index));
|
||||
}
|
||||
|
||||
private boolean isCorrectChild(int index) {
|
||||
return isCorrect(parentIndex(index), index);
|
||||
}
|
||||
|
||||
private boolean isCorrect(int parentIndex, int childIndex) {
|
||||
if (!isValidIndex(parentIndex) || !isValidIndex(childIndex)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return elementAt(parentIndex).compareTo(elementAt(childIndex)) < 0;
|
||||
}
|
||||
|
||||
private boolean isValidIndex(int index) {
|
||||
return index < elements.size();
|
||||
}
|
||||
|
||||
private void swap(int index1, int index2) {
|
||||
E element1 = elementAt(index1);
|
||||
E element2 = elementAt(index2);
|
||||
elements.set(index1, element2);
|
||||
elements.set(index2, element1);
|
||||
}
|
||||
|
||||
private E elementAt(int index) {
|
||||
return elements.get(index);
|
||||
}
|
||||
|
||||
private int parentIndex(int index) {
|
||||
return (index - 1) / 2;
|
||||
}
|
||||
|
||||
private int leftChildIndex(int index) {
|
||||
return 2 * index + 1;
|
||||
}
|
||||
|
||||
private int rightChildIndex(int index) {
|
||||
return 2 * index + 2;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.baeldung.algorithms.insertionsort;
|
||||
|
||||
public class InsertionSort {
|
||||
|
||||
public static void insertionSortImperative(int[] input) {
|
||||
for (int i = 1; i < input.length; i++) {
|
||||
int key = input[i];
|
||||
int j = i - 1;
|
||||
while (j >= 0 && input[j] > key) {
|
||||
input[j + 1] = input[j];
|
||||
j = j - 1;
|
||||
}
|
||||
input[j + 1] = key;
|
||||
}
|
||||
}
|
||||
|
||||
public static void insertionSortRecursive(int[] input) {
|
||||
insertionSortRecursive(input, input.length);
|
||||
}
|
||||
|
||||
private static void insertionSortRecursive(int[] input, int i) {
|
||||
// base case
|
||||
if (i <= 1) {
|
||||
return;
|
||||
}
|
||||
|
||||
// sort the first i - 1 elements of the array
|
||||
insertionSortRecursive(input, i - 1);
|
||||
|
||||
// then find the correct position of the element at position i
|
||||
int key = input[i - 1];
|
||||
int j = i - 2;
|
||||
// shifting the elements from their position by 1
|
||||
while (j >= 0 && input[j] > key) {
|
||||
input[j + 1] = input[j];
|
||||
j = j - 1;
|
||||
}
|
||||
// inserting the key at the appropriate position
|
||||
input[j + 1] = key;
|
||||
}
|
||||
}
|
||||
+127
@@ -0,0 +1,127 @@
|
||||
package com.baeldung.algorithms.conversion;
|
||||
|
||||
import static org.junit.Assert.assertArrayEquals;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import org.apache.commons.codec.DecoderException;
|
||||
import org.hamcrest.text.IsEqualIgnoringCase;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.algorithms.conversion.HexStringConverter;
|
||||
|
||||
public class ByteArrayConverterUnitTest {
|
||||
|
||||
private HexStringConverter hexStringConverter;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
hexStringConverter = new HexStringConverter();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldEncodeByteArrayToHexStringUsingBigIntegerToString() {
|
||||
byte[] bytes = getSampleBytes();
|
||||
String hexString = getSampleHexString();
|
||||
if(hexString.charAt(0) == '0') {
|
||||
hexString = hexString.substring(1);
|
||||
}
|
||||
String output = hexStringConverter.encodeUsingBigIntegerToString(bytes);
|
||||
assertThat(output, IsEqualIgnoringCase.equalToIgnoringCase(hexString));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldEncodeByteArrayToHexStringUsingBigIntegerStringFormat() {
|
||||
byte[] bytes = getSampleBytes();
|
||||
String hexString = getSampleHexString();
|
||||
String output = hexStringConverter.encodeUsingBigIntegerStringFormat(bytes);
|
||||
assertThat(output, IsEqualIgnoringCase.equalToIgnoringCase(hexString));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldDecodeHexStringToByteArrayUsingBigInteger() {
|
||||
byte[] bytes = getSampleBytes();
|
||||
String hexString = getSampleHexString();
|
||||
byte[] output = hexStringConverter.decodeUsingBigInteger(hexString);
|
||||
assertArrayEquals(bytes, output);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldEncodeByteArrayToHexStringUsingCharacterConversion() {
|
||||
byte[] bytes = getSampleBytes();
|
||||
String hexString = getSampleHexString();
|
||||
String output = hexStringConverter.encodeHexString(bytes);
|
||||
assertThat(output, IsEqualIgnoringCase.equalToIgnoringCase(hexString));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldDecodeHexStringToByteArrayUsingCharacterConversion() {
|
||||
byte[] bytes = getSampleBytes();
|
||||
String hexString = getSampleHexString();
|
||||
byte[] output = hexStringConverter.decodeHexString(hexString);
|
||||
assertArrayEquals(bytes, output);
|
||||
}
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void shouldDecodeHexToByteWithInvalidHexCharacter() {
|
||||
hexStringConverter.hexToByte("fg");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldEncodeByteArrayToHexStringDataTypeConverter() {
|
||||
byte[] bytes = getSampleBytes();
|
||||
String hexString = getSampleHexString();
|
||||
String output = hexStringConverter.encodeUsingDataTypeConverter(bytes);
|
||||
assertThat(output, IsEqualIgnoringCase.equalToIgnoringCase(hexString));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldDecodeHexStringToByteArrayUsingDataTypeConverter() {
|
||||
byte[] bytes = getSampleBytes();
|
||||
String hexString = getSampleHexString();
|
||||
byte[] output = hexStringConverter.decodeUsingDataTypeConverter(hexString);
|
||||
assertArrayEquals(bytes, output);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldEncodeByteArrayToHexStringUsingGuava() {
|
||||
byte[] bytes = getSampleBytes();
|
||||
String hexString = getSampleHexString();
|
||||
String output = hexStringConverter.encodeUsingGuava(bytes);
|
||||
assertThat(output, IsEqualIgnoringCase.equalToIgnoringCase(hexString));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldDecodeHexStringToByteArrayUsingGuava() {
|
||||
byte[] bytes = getSampleBytes();
|
||||
String hexString = getSampleHexString();
|
||||
byte[] output = hexStringConverter.decodeUsingGuava(hexString);
|
||||
assertArrayEquals(bytes, output);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldEncodeByteArrayToHexStringUsingApacheCommons() throws DecoderException {
|
||||
byte[] bytes = getSampleBytes();
|
||||
String hexString = getSampleHexString();
|
||||
String output = hexStringConverter.encodeUsingApacheCommons(bytes);
|
||||
assertThat(output, IsEqualIgnoringCase.equalToIgnoringCase(hexString));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldDecodeHexStringToByteArrayUsingApacheCommons() throws DecoderException {
|
||||
byte[] bytes = getSampleBytes();
|
||||
String hexString = getSampleHexString();
|
||||
byte[] output = hexStringConverter.decodeUsingApacheCommons(hexString);
|
||||
assertArrayEquals(bytes, output);
|
||||
}
|
||||
|
||||
private String getSampleHexString() {
|
||||
return "0af50c0e2d10";
|
||||
}
|
||||
|
||||
private byte[] getSampleBytes() {
|
||||
return new byte[] { 10, -11, 12, 14, 45, 16 };
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.baeldung.algorithms.heapsort;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class HeapUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenNotEmptyHeap_whenPopCalled_thenItShouldReturnSmallestElement() {
|
||||
// given
|
||||
Heap<Integer> heap = Heap.of(3, 5, 1, 4, 2);
|
||||
|
||||
// when
|
||||
int head = heap.pop();
|
||||
|
||||
// then
|
||||
assertThat(head).isEqualTo(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNotEmptyIterable_whenSortCalled_thenItShouldReturnElementsInSortedList() {
|
||||
// given
|
||||
List<Integer> elements = Arrays.asList(3, 5, 1, 4, 2);
|
||||
|
||||
// when
|
||||
List<Integer> sortedElements = Heap.sort(elements);
|
||||
|
||||
// then
|
||||
assertThat(sortedElements).isEqualTo(Arrays.asList(1, 2, 3, 4, 5));
|
||||
}
|
||||
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package com.baeldung.algorithms.insertionsort;
|
||||
|
||||
import com.baeldung.algorithms.insertionsort.InsertionSort;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertArrayEquals;
|
||||
|
||||
public class InsertionSortUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenUnsortedArray_whenInsertionSortImperative_thenSortedAsc() {
|
||||
int[] input = {6, 2, 3, 4, 5, 1};
|
||||
InsertionSort.insertionSortImperative(input);
|
||||
int[] expected = {1, 2, 3, 4, 5, 6};
|
||||
assertArrayEquals("the two arrays are not equal", expected, input);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUnsortedArray_whenInsertionSortRecursive_thenSortedAsc() {
|
||||
int[] input = {6, 4, 5, 2, 3, 1};
|
||||
InsertionSort.insertionSortRecursive(input);
|
||||
int[] expected = {1, 2, 3, 4, 5, 6};
|
||||
assertArrayEquals("the two arrays are not equal", expected, input);
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -9,4 +9,4 @@
|
||||
- [Integration Testing with a Local DynamoDB Instance](http://www.baeldung.com/dynamodb-local-integration-tests)
|
||||
- [Using the JetS3t Java Client With Amazon S3](http://www.baeldung.com/jets3t-amazon-s3)
|
||||
- [Managing Amazon SQS Queues in Java](http://www.baeldung.com/aws-queues-java)
|
||||
|
||||
- [Guide to AWS Aurora RDS with Java](https://www.baeldung.com/aws-aurora-rds-java)
|
||||
|
||||
-46
@@ -1,46 +0,0 @@
|
||||
package com.baeldung.internationalization;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.time.format.FormatStyle;
|
||||
import java.util.Locale;
|
||||
import java.util.TimeZone;
|
||||
|
||||
public class DateTimeFormatterUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenDefaultUsLocaleAndDateTimeAndPattern_whenFormatWithDifferentLocales_thenGettingLocalizedDateTimes() {
|
||||
Locale.setDefault(Locale.US);
|
||||
LocalDateTime localDateTime = LocalDateTime.of(2018, 1, 1, 10, 15, 50, 500);
|
||||
String pattern = "dd-MMMM-yyyy HH:mm:ss.SSS";
|
||||
|
||||
DateTimeFormatter defaultTimeFormatter = DateTimeFormatter.ofPattern(pattern);
|
||||
DateTimeFormatter plTimeFormatter = DateTimeFormatter.ofPattern(pattern, new Locale("pl", "PL"));
|
||||
DateTimeFormatter deTimeFormatter = DateTimeFormatter.ofPattern(pattern).withLocale(Locale.GERMANY);
|
||||
|
||||
Assert.assertEquals("01-January-2018 10:15:50.000", defaultTimeFormatter.format(localDateTime));
|
||||
Assert.assertEquals("01-stycznia-2018 10:15:50.000", plTimeFormatter.format(localDateTime));
|
||||
Assert.assertEquals("01-Januar-2018 10:15:50.000", deTimeFormatter.format(localDateTime));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDateTimeAndTimeZone_whenFormatWithDifferentLocales_thenGettingLocalizedZonedDateTimes() {
|
||||
Locale.setDefault(Locale.US);
|
||||
LocalDateTime localDateTime = LocalDateTime.of(2018, 1, 1, 10, 15, 50, 500);
|
||||
ZoneId losAngelesTimeZone = TimeZone.getTimeZone("America/Los_Angeles").toZoneId();
|
||||
|
||||
DateTimeFormatter localizedFormatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL);
|
||||
DateTimeFormatter frLocalizedFormatter =
|
||||
DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL).withLocale(Locale.FRANCE);
|
||||
String formattedDateTime = localizedFormatter.format(ZonedDateTime.of(localDateTime, losAngelesTimeZone));
|
||||
String frFormattedDateTime = frLocalizedFormatter.format(ZonedDateTime.of(localDateTime, losAngelesTimeZone));
|
||||
|
||||
Assert.assertEquals("Monday, January 1, 2018 10:15:50 AM PST", formattedDateTime);
|
||||
Assert.assertEquals("lundi 1 janvier 2018 10 h 15 PST", frFormattedDateTime);
|
||||
}
|
||||
}
|
||||
@@ -26,3 +26,4 @@
|
||||
- [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)
|
||||
- [Java 9 Platform Logging API](https://www.baeldung.com/java-9-logging-api)
|
||||
- [Guide to java.lang.Process API](https://www.baeldung.com/java-process-api)
|
||||
|
||||
@@ -52,3 +52,6 @@
|
||||
- [Performance of contains() in a HashSet vs ArrayList](https://www.baeldung.com/java-hashset-arraylist-contains-performance)
|
||||
- [Get the Key for a Value from a Java Map](https://www.baeldung.com/java-map-key-from-value)
|
||||
- [Time Complexity of Java Collections](https://www.baeldung.com/java-collections-complexity)
|
||||
- [Sort a HashMap in Java](https://www.baeldung.com/java-hashmap-sort)
|
||||
- [Finding the Highest Value in a Java Map](https://www.baeldung.com/java-find-map-max)
|
||||
- [Operating on and Removing an Item from Stream](https://www.baeldung.com/java-use-remove-item-stream)
|
||||
|
||||
@@ -1,90 +1,88 @@
|
||||
<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</groupId>
|
||||
<artifactId>core-java-collections</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
<name>core-java-collections</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-java</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../parent-java</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>net.sourceforge.collections</groupId>
|
||||
<artifactId>collections-generic</artifactId>
|
||||
<version>${collections-generic.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-collections4</artifactId>
|
||||
<version>${commons-collections4.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.jayway.awaitility</groupId>
|
||||
<artifactId>awaitility</artifactId>
|
||||
<version>${avaitility.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.eclipse.collections</groupId>
|
||||
<artifactId>eclipse-collections</artifactId>
|
||||
<version>${eclipse.collections.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.platform</groupId>
|
||||
<artifactId>junit-platform-runner</artifactId>
|
||||
<version>${junit.platform.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-core</artifactId>
|
||||
<version>${openjdk.jmh.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-generator-annprocess</artifactId>
|
||||
<version>${openjdk.jmh.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-exec</artifactId>
|
||||
<version>1.3</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>one.util</groupId>
|
||||
<artifactId>streamex</artifactId>
|
||||
<version>0.6.5</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
|
||||
<properties>
|
||||
<openjdk.jmh.version>1.19</openjdk.jmh.version>
|
||||
<junit.platform.version>1.2.0</junit.platform.version>
|
||||
<commons-lang3.version>3.5</commons-lang3.version>
|
||||
<commons-collections4.version>4.1</commons-collections4.version>
|
||||
<collections-generic.version>4.01</collections-generic.version>
|
||||
<avaitility.version>1.7.0</avaitility.version>
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
<eclipse.collections.version>7.1.0</eclipse.collections.version>
|
||||
</properties>
|
||||
</project>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>core-java-collections</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
<name>core-java-collections</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-java</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../parent-java</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>net.sourceforge.collections</groupId>
|
||||
<artifactId>collections-generic</artifactId>
|
||||
<version>${collections-generic.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-collections4</artifactId>
|
||||
<version>${commons-collections4.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.jayway.awaitility</groupId>
|
||||
<artifactId>awaitility</artifactId>
|
||||
<version>${avaitility.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.eclipse.collections</groupId>
|
||||
<artifactId>eclipse-collections</artifactId>
|
||||
<version>${eclipse.collections.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.platform</groupId>
|
||||
<artifactId>junit-platform-runner</artifactId>
|
||||
<version>${junit.platform.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-core</artifactId>
|
||||
<version>${openjdk.jmh.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-generator-annprocess</artifactId>
|
||||
<version>${openjdk.jmh.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-exec</artifactId>
|
||||
<version>1.3</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>one.util</groupId>
|
||||
<artifactId>streamex</artifactId>
|
||||
<version>0.6.5</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<openjdk.jmh.version>1.19</openjdk.jmh.version>
|
||||
<junit.platform.version>1.2.0</junit.platform.version>
|
||||
<commons-lang3.version>3.5</commons-lang3.version>
|
||||
<commons-collections4.version>4.1</commons-collections4.version>
|
||||
<collections-generic.version>4.01</collections-generic.version>
|
||||
<avaitility.version>1.7.0</avaitility.version>
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
<eclipse.collections.version>7.1.0</eclipse.collections.version>
|
||||
</properties>
|
||||
</project>
|
||||
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
package com.baeldung.convertcollectiontoarraylist;
|
||||
|
||||
/**
|
||||
* This POJO is the element type of our collection. It has a deepCopy() method.
|
||||
*
|
||||
* @author chris
|
||||
*/
|
||||
public class Foo {
|
||||
|
||||
private int id;
|
||||
private String name;
|
||||
private Foo parent;
|
||||
|
||||
public Foo() {
|
||||
}
|
||||
|
||||
public Foo(int id, String name, Foo parent) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
this.parent = parent;
|
||||
}
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Foo getParent() {
|
||||
return parent;
|
||||
}
|
||||
|
||||
public void setParent(Foo parent) {
|
||||
this.parent = parent;
|
||||
}
|
||||
|
||||
public Foo deepCopy() {
|
||||
return new Foo(
|
||||
this.id, this.name, this.parent != null ? this.parent.deepCopy() : null);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.baeldung.enumset;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.EnumSet;
|
||||
import java.util.List;
|
||||
|
||||
public class EnumSets {
|
||||
|
||||
public enum Color {
|
||||
RED, YELLOW, GREEN, BLUE, BLACK, WHITE
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
EnumSet<Color> allColors = EnumSet.allOf(Color.class);
|
||||
System.out.println(allColors);
|
||||
|
||||
EnumSet<Color> noColors = EnumSet.noneOf(Color.class);
|
||||
System.out.println(noColors);
|
||||
|
||||
EnumSet<Color> blackAndWhite = EnumSet.of(Color.BLACK, Color.WHITE);
|
||||
System.out.println(blackAndWhite);
|
||||
|
||||
EnumSet<Color> noBlackOrWhite = EnumSet.complementOf(blackAndWhite);
|
||||
System.out.println(noBlackOrWhite);
|
||||
|
||||
EnumSet<Color> range = EnumSet.range(Color.YELLOW, Color.BLUE);
|
||||
System.out.println(range);
|
||||
|
||||
EnumSet<Color> blackAndWhiteCopy = EnumSet.copyOf(EnumSet.of(Color.BLACK, Color.WHITE));
|
||||
System.out.println(blackAndWhiteCopy);
|
||||
|
||||
List<Color> colorsList = new ArrayList<>();
|
||||
colorsList.add(Color.RED);
|
||||
EnumSet<Color> listCopy = EnumSet.copyOf(colorsList);
|
||||
System.out.println(listCopy);
|
||||
|
||||
EnumSet<Color> set = EnumSet.noneOf(Color.class);
|
||||
set.add(Color.RED);
|
||||
set.add(Color.YELLOW);
|
||||
set.contains(Color.RED);
|
||||
set.forEach(System.out::println);
|
||||
set.remove(Color.RED);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.baeldung.removal;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
|
||||
public class CollectionRemoveIf {
|
||||
|
||||
public static void main(String args[]) {
|
||||
Collection<String> names = new ArrayList<>();
|
||||
names.add("John");
|
||||
names.add("Ana");
|
||||
names.add("Mary");
|
||||
names.add("Anthony");
|
||||
names.add("Mark");
|
||||
|
||||
names.removeIf(e -> e.startsWith("A"));
|
||||
System.out.println(String.join(",", names));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.baeldung.removal;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Iterator;
|
||||
|
||||
public class Iterators {
|
||||
|
||||
public static void main(String args[]) {
|
||||
Collection<String> names = new ArrayList<>();
|
||||
names.add("John");
|
||||
names.add("Ana");
|
||||
names.add("Mary");
|
||||
names.add("Anthony");
|
||||
names.add("Mark");
|
||||
|
||||
Iterator<String> i = names.iterator();
|
||||
|
||||
while (i.hasNext()) {
|
||||
String e = i.next();
|
||||
if (e.startsWith("A")) {
|
||||
i.remove();
|
||||
}
|
||||
}
|
||||
|
||||
System.out.println(String.join(",", names));
|
||||
}
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package com.baeldung.removal;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class StreamFilterAndCollector {
|
||||
|
||||
public static void main(String args[]) {
|
||||
Collection<String> names = new ArrayList<>();
|
||||
names.add("John");
|
||||
names.add("Ana");
|
||||
names.add("Mary");
|
||||
names.add("Anthony");
|
||||
names.add("Mark");
|
||||
|
||||
Collection<String> filteredCollection = names
|
||||
.stream()
|
||||
.filter(e -> !e.startsWith("A"))
|
||||
.collect(Collectors.toList());
|
||||
System.out.println(String.join(",", filteredCollection));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.baeldung.removal;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class StreamPartitioningBy {
|
||||
|
||||
public static void main(String args[]) {
|
||||
Collection<String> names = new ArrayList<>();
|
||||
names.add("John");
|
||||
names.add("Ana");
|
||||
names.add("Mary");
|
||||
names.add("Anthony");
|
||||
names.add("Mark");
|
||||
|
||||
Map<Boolean, List<String>> classifiedElements = names
|
||||
.stream()
|
||||
.collect(Collectors.partitioningBy((String e) -> !e.startsWith("A")));
|
||||
|
||||
String matching = String.join(",", classifiedElements.get(Boolean.TRUE));
|
||||
String nonMatching = String.join(",", classifiedElements.get(Boolean.FALSE));
|
||||
System.out.println("Matching elements: " + matching);
|
||||
System.out.println("Non matching elements: " + nonMatching);
|
||||
}
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package com.baeldung.synchronizedcollections.application;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
public class Application {
|
||||
|
||||
private static final Logger LOGGER = Logger.getLogger(Application.class.getName());
|
||||
|
||||
public static void main(String[] args) throws InterruptedException {
|
||||
List<Integer> syncCollection = Collections.synchronizedList(Arrays.asList(1, 2, 3, 4, 5, 6));
|
||||
synchronized (syncCollection) {
|
||||
syncCollection.forEach((e) -> {LOGGER.info(e.toString());});
|
||||
}
|
||||
}
|
||||
}
|
||||
+148
@@ -0,0 +1,148 @@
|
||||
package com.baeldung.convertcollectiontoarraylist;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashSet;
|
||||
import java.util.Iterator;
|
||||
import static java.util.stream.Collectors.toCollection;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author chris
|
||||
*/
|
||||
public class FooUnitTest {
|
||||
private static Collection<Foo> srcCollection = new HashSet<>();
|
||||
|
||||
public FooUnitTest() {
|
||||
}
|
||||
|
||||
@BeforeClass
|
||||
public static void setUpClass() {
|
||||
int i = 0;
|
||||
Foo john = new Foo(i++, "John", null);
|
||||
Foo mary = new Foo(i++, "Mary", null);
|
||||
Foo sam = new Foo(i++, "Sam", john);
|
||||
Foo alice = new Foo(i++, "Alice", john);
|
||||
Foo buffy = new Foo(i++, "Buffy", sam);
|
||||
srcCollection.add(john);
|
||||
srcCollection.add(mary);
|
||||
srcCollection.add(sam);
|
||||
srcCollection.add(alice);
|
||||
srcCollection.add(buffy);
|
||||
|
||||
// make sure the collection isn't sorted accidentally
|
||||
assertFalse("Oops: source collection is already sorted!", isSorted(srcCollection));
|
||||
}
|
||||
|
||||
/**
|
||||
* Section 3. Using the ArrayList Constructor
|
||||
*/
|
||||
@Test
|
||||
public void whenUsingConstructor_thenVerifyShallowCopy() {
|
||||
ArrayList<Foo> newList = new ArrayList<>(srcCollection);
|
||||
verifyShallowCopy(srcCollection, newList);
|
||||
}
|
||||
|
||||
/**
|
||||
* Section 4. Using the Streams API
|
||||
*/
|
||||
@Test
|
||||
public void whenUsingStream_thenVerifyShallowCopy() {
|
||||
ArrayList<Foo> newList = srcCollection.stream().collect(toCollection(ArrayList::new));
|
||||
|
||||
verifyShallowCopy(srcCollection, newList);
|
||||
}
|
||||
|
||||
/**
|
||||
* Section 5. Deep Copy
|
||||
*/
|
||||
@Test
|
||||
public void whenUsingDeepCopy_thenVerifyDeepCopy() {
|
||||
ArrayList<Foo> newList = srcCollection.stream()
|
||||
.map(foo -> foo.deepCopy())
|
||||
.collect(toCollection(ArrayList::new));
|
||||
|
||||
verifyDeepCopy(srcCollection, newList);
|
||||
}
|
||||
|
||||
/**
|
||||
* Section 6. Controlling the List Order
|
||||
*/
|
||||
@Test
|
||||
public void whenUsingSortedStream_thenVerifySortOrder() {
|
||||
ArrayList<Foo> newList = srcCollection.stream()
|
||||
.sorted(Comparator.comparing(Foo::getName))
|
||||
.collect(toCollection(ArrayList::new));
|
||||
|
||||
assertTrue("ArrayList is not sorted by name", isSorted(newList));
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify that the contents of the two collections are the same
|
||||
* @param a
|
||||
* @param b
|
||||
*/
|
||||
private void verifyShallowCopy(Collection a, Collection b) {
|
||||
assertEquals("Collections have different lengths", a.size(), b.size());
|
||||
Iterator<Foo> iterA = a.iterator();
|
||||
Iterator<Foo> iterB = b.iterator();
|
||||
while (iterA.hasNext()) {
|
||||
// use '==' to test instance identity
|
||||
assertTrue("Foo instances differ!", iterA.next() == iterB.next());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify that the contents of the two collections are the same
|
||||
* @param a
|
||||
* @param b
|
||||
*/
|
||||
private void verifyDeepCopy(Collection a, Collection b) {
|
||||
assertEquals("Collections have different lengths", a.size(), b.size());
|
||||
Iterator<Foo> iterA = a.iterator();
|
||||
Iterator<Foo> iterB = b.iterator();
|
||||
while (iterA.hasNext()) {
|
||||
Foo nextA = iterA.next();
|
||||
Foo nextB = iterB.next();
|
||||
// should not be same instance
|
||||
assertFalse("Foo instances are the same!", nextA == nextB);
|
||||
// but should have same content
|
||||
assertFalse("Foo instances have different content!", fooDiff(nextA, nextB));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Return true if the contents of a and b differ. Test parent recursively
|
||||
* @param a
|
||||
* @param b
|
||||
* @return False if the two items are the same
|
||||
*/
|
||||
private boolean fooDiff(Foo a, Foo b) {
|
||||
if (a != null && b != null) {
|
||||
return a.getId() != b.getId()
|
||||
|| !a.getName().equals(b.getName())
|
||||
|| fooDiff(a.getParent(), b.getParent());
|
||||
}
|
||||
return !(a == null && b == null);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param c collection of Foo
|
||||
* @return true if the collection is sorted by name
|
||||
*/
|
||||
private static boolean isSorted(Collection<Foo> c) {
|
||||
String prevName = null;
|
||||
for (Foo foo : c) {
|
||||
if (prevName == null || foo.getName().compareTo(prevName) > 0) {
|
||||
prevName = foo.getName();
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
+89
@@ -0,0 +1,89 @@
|
||||
package com.baeldung.findItems;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.text.ParseException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class FindItemsBasedOnOtherStreamUnitTest {
|
||||
|
||||
private List<Employee> employeeList = new ArrayList<Employee>();
|
||||
|
||||
private List<Department> departmentList = new ArrayList<Department>();
|
||||
|
||||
@Test
|
||||
public void givenDepartmentList_thenEmployeeListIsFilteredCorrectly() {
|
||||
Integer expectedId = 1002;
|
||||
|
||||
populate(employeeList, departmentList);
|
||||
|
||||
List<Employee> filteredList = employeeList.stream()
|
||||
.filter(empl -> departmentList.stream()
|
||||
.anyMatch(dept -> dept.getDepartment()
|
||||
.equals("sales") && empl.getEmployeeId()
|
||||
.equals(dept.getEmployeeId())))
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertEquals(expectedId, filteredList.get(0)
|
||||
.getEmployeeId());
|
||||
}
|
||||
|
||||
private void populate(List<Employee> EmplList, List<Department> deptList) {
|
||||
Employee employee1 = new Employee(1001, "empl1");
|
||||
Employee employee2 = new Employee(1002, "empl2");
|
||||
Employee employee3 = new Employee(1003, "empl3");
|
||||
|
||||
Collections.addAll(EmplList, employee1, employee2, employee3);
|
||||
|
||||
Department department1 = new Department(1002, "sales");
|
||||
Department department2 = new Department(1003, "marketing");
|
||||
Department department3 = new Department(1004, "sales");
|
||||
|
||||
Collections.addAll(deptList, department1, department2, department3);
|
||||
}
|
||||
}
|
||||
|
||||
class Employee {
|
||||
private Integer employeeId;
|
||||
private String employeeName;
|
||||
|
||||
Employee(Integer employeeId, String employeeName) {
|
||||
super();
|
||||
this.employeeId = employeeId;
|
||||
this.employeeName = employeeName;
|
||||
}
|
||||
|
||||
Integer getEmployeeId() {
|
||||
return employeeId;
|
||||
}
|
||||
|
||||
public String getEmployeeName() {
|
||||
return employeeName;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class Department {
|
||||
private Integer employeeId;
|
||||
private String department;
|
||||
|
||||
Department(Integer employeeId, String department) {
|
||||
super();
|
||||
this.employeeId = employeeId;
|
||||
this.department = department;
|
||||
}
|
||||
|
||||
Integer getEmployeeId() {
|
||||
return employeeId;
|
||||
}
|
||||
|
||||
String getDepartment() {
|
||||
return department;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
package com.baeldung.java.map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.apache.commons.collections4.MultiMap;
|
||||
import org.apache.commons.collections4.MultiMapUtils;
|
||||
import org.apache.commons.collections4.MultiValuedMap;
|
||||
import org.apache.commons.collections4.map.MultiValueMap;
|
||||
import org.apache.commons.collections4.multimap.ArrayListValuedHashMap;
|
||||
import org.apache.commons.collections4.multimap.HashSetValuedHashMap;
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.google.common.collect.ArrayListMultimap;
|
||||
import com.google.common.collect.LinkedHashMultimap;
|
||||
import com.google.common.collect.Multimap;
|
||||
import com.google.common.collect.TreeMultimap;
|
||||
|
||||
|
||||
public class KeyCheckTest {
|
||||
|
||||
@Test
|
||||
public void whenKeyIsPresent_thenContainsKeyReturnsTrue() {
|
||||
Map<String, String> map = Collections.singletonMap("key", "value");
|
||||
|
||||
assertTrue(map.containsKey("key"));
|
||||
assertFalse(map.containsKey("missing"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenKeyHasNullValue_thenGetStillWorks() {
|
||||
Map<String, String> map = Collections.singletonMap("nothing", null);
|
||||
|
||||
assertTrue(map.containsKey("nothing"));
|
||||
assertNull(map.get("nothing"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.baeldung.java.map;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.Map;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class KeyCheckUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenKeyIsPresent_thenContainsKeyReturnsTrue() {
|
||||
Map<String, String> map = Collections.singletonMap("key", "value");
|
||||
|
||||
assertTrue(map.containsKey("key"));
|
||||
assertFalse(map.containsKey("missing"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenKeyHasNullValue_thenGetStillWorks() {
|
||||
Map<String, String> map = Collections.singletonMap("nothing", null);
|
||||
|
||||
assertTrue(map.containsKey("nothing"));
|
||||
assertNull(map.get("nothing"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package com.baeldung.removal;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.hamcrest.Matchers.is;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
public class RemovalUnitTest {
|
||||
|
||||
Collection<String> names;
|
||||
Collection<String> expected;
|
||||
Collection<String> removed;
|
||||
|
||||
@Before
|
||||
public void setupTestData() {
|
||||
names = new ArrayList<>();
|
||||
expected = new ArrayList<>();
|
||||
removed = new ArrayList<>();
|
||||
|
||||
names.add("John");
|
||||
names.add("Ana");
|
||||
names.add("Mary");
|
||||
names.add("Anthony");
|
||||
names.add("Mark");
|
||||
|
||||
expected.add("John");
|
||||
expected.add("Mary");
|
||||
expected.add("Mark");
|
||||
|
||||
removed.add("Ana");
|
||||
removed.add("Anthony");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCollectionOfNames_whenUsingIteratorToRemoveAllNamesStartingWithLetterA_finalListShouldContainNoNamesStartingWithLetterA() {
|
||||
Iterator<String> i = names.iterator();
|
||||
|
||||
while (i.hasNext()) {
|
||||
String e = i.next();
|
||||
if (e.startsWith("A")) {
|
||||
i.remove();
|
||||
}
|
||||
}
|
||||
|
||||
assertThat(names, is(expected));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCollectionOfNames_whenUsingRemoveIfToRemoveAllNamesStartingWithLetterA_finalListShouldContainNoNamesStartingWithLetterA() {
|
||||
names.removeIf(e -> e.startsWith("A"));
|
||||
assertThat(names, is(expected));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCollectionOfNames_whenUsingStreamToFilterAllNamesStartingWithLetterA_finalListShouldContainNoNamesStartingWithLetterA() {
|
||||
Collection<String> filteredCollection = names
|
||||
.stream()
|
||||
.filter(e -> !e.startsWith("A"))
|
||||
.collect(Collectors.toList());
|
||||
assertThat(filteredCollection, is(expected));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCollectionOfNames_whenUsingStreamAndPartitioningByToFindNamesThatStartWithLetterA_shouldFind3MatchingAnd2NonMatching() {
|
||||
Map<Boolean, List<String>> classifiedElements = names
|
||||
.stream()
|
||||
.collect(Collectors.partitioningBy((String e) -> !e.startsWith("A")));
|
||||
|
||||
assertThat(classifiedElements.get(Boolean.TRUE), is(expected));
|
||||
assertThat(classifiedElements.get(Boolean.FALSE), is(removed));
|
||||
}
|
||||
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
package com.baeldung.synchronizedcollections.test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import org.junit.Test;
|
||||
|
||||
public class SynchronizedCollectionUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenSynchronizedCollection_whenTwoThreadsAddElements_thenCorrectCollectionSize() throws InterruptedException {
|
||||
Collection<Integer> syncCollection = Collections.synchronizedCollection(new ArrayList<>());
|
||||
|
||||
Runnable listOperations = () -> {
|
||||
syncCollection.addAll(Arrays.asList(1, 2, 3, 4, 5, 6));
|
||||
};
|
||||
Thread thread1 = new Thread(listOperations);
|
||||
Thread thread2 = new Thread(listOperations);
|
||||
thread1.start();
|
||||
thread2.start();
|
||||
thread1.join();
|
||||
thread2.join();
|
||||
|
||||
assertThat(syncCollection.size()).isEqualTo(12);
|
||||
}
|
||||
}
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
package com.baeldung.synchronizedcollections.test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import org.junit.Test;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
public class SynchronizedListUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenSynchronizedList_whenTwoThreadsAddElements_thenCorrectListSize() throws InterruptedException {
|
||||
List<Integer> syncList = Collections.synchronizedList(new ArrayList<>());
|
||||
|
||||
Runnable listOperations = () -> {
|
||||
syncList.addAll(Arrays.asList(1, 2, 3, 4, 5, 6));
|
||||
};
|
||||
Thread thread1 = new Thread(listOperations);
|
||||
Thread thread2 = new Thread(listOperations);
|
||||
thread1.start();
|
||||
thread2.start();
|
||||
thread1.join();
|
||||
thread2.join();
|
||||
|
||||
assertThat(syncList.size()).isEqualTo(12);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStringList_whenTwoThreadsIterateOnSynchronizedList_thenCorrectResult() throws InterruptedException {
|
||||
List<String> syncCollection = Collections.synchronizedList(Arrays.asList("a", "b", "c"));
|
||||
List<String> uppercasedCollection = new ArrayList<>();
|
||||
|
||||
Runnable listOperations = () -> {
|
||||
synchronized (syncCollection) {
|
||||
syncCollection.forEach((e) -> {
|
||||
uppercasedCollection.add(e.toUpperCase());
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
Thread thread1 = new Thread(listOperations);
|
||||
Thread thread2 = new Thread(listOperations);
|
||||
thread1.start();
|
||||
thread2.start();
|
||||
thread1.join();
|
||||
thread2.join();
|
||||
|
||||
assertThat(uppercasedCollection.get(0)).isEqualTo("A");
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user