Merge branch 'master' of github.com:eugenp/tutorials

This commit is contained in:
akash.pandey 2018-10-25 08:17:09 +05:30
commit 121969da27
792 changed files with 11414 additions and 2335 deletions

2
.gitignore vendored
View File

@ -62,3 +62,5 @@ jmeter/src/main/resources/*-JMeter.csv
**/dist
**/tmp
**/out-tsc
**/nbproject/
**/nb-configuration.xml

View File

@ -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

View File

@ -2,41 +2,37 @@
The "REST with Spring" Classes
==============================
Here's the Master Class of REST With Spring (price changes permanently next Friday): <br/>
**[>> THE REST WITH SPRING MASTER CLASS](http://www.baeldung.com/rest-with-spring-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=rws#master-class)**
Here's the Master Class of REST With Spring (along with the newly announced Boot 2 material): <br/>
**[>> THE REST WITH SPRING - MASTER CLASS](http://www.baeldung.com/rest-with-spring-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=rws#master-class)**
And here's the Master Class of Learn Spring Security: <br/>
**[>> LEARN SPRING SECURITY MASTER CLASS](http://www.baeldung.com/learn-spring-security-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=lss#master-class)**
**[>> LEARN SPRING SECURITY - MASTER CLASS](http://www.baeldung.com/learn-spring-security-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=lss#master-class)**
Spring Tutorials
Java and Spring Tutorials
================
This project is **a collection of small and focused tutorials** each covering a single and well defined area of development.
Most of the tutorial projects are focused on the `Spring Framework` (and `Spring Security`).
This project is **a collection of small and focused tutorials** - each covering a single and well defined area of development in the Java ecosystem.
A strong focus of these is, of course, the Spring Framework - Spring, Spring Boot and Spring Securiyt.
In additional to Spring, the following technologies are in focus: `core Java`, `Jackson`, `HttpClient`, `Guava`.
Building the project
====================
To do the full build, do: `mvn install -Pdefault -Dgib.enabled=false`
Working with the code in Eclipse
================================
Any IDE can be used to work with the projects, but if you're using Eclipse, consider the following.
- import the included **formatter** in Eclipse:
`https://github.com/eugenp/tutorials/tree/master/eclipse`
Building a single module
====================
To build a specific module run the command: `mvn clean install -Dgib.enabled=false` in the module directory
Running a Spring Boot module
====================
To run a Spring Boot module run the command: `mvn spring-boot:run -Dgib.enabled=false` in the module directory
CI - Jenkins
================================
This tutorials project is being built **[>> HERE](https://rest-security.ci.cloudbees.com/job/tutorials-unit/)**
### Relevant Articles:
================================
- [Apache Maven Standard Directory Layout](http://www.baeldung.com/maven-directory-structure)
- [Apache Maven Tutorial](http://www.baeldung.com/maven)
- [Designing a User Friendly Java Library](http://www.baeldung.com/design-a-user-friendly-java-library)

View File

@ -28,3 +28,9 @@
- [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)
- [Quicksort Algorithm Implementation in Java](https://www.baeldung.com/java-quicksort)
- [Insertion Sort in Java](https://www.baeldung.com/java-insertion-sort)
- [Converting Between Byte Arrays and Hexadecimal Strings in Java](https://www.baeldung.com/java-byte-arrays-hex-strings)

View File

@ -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>

View File

@ -7,7 +7,7 @@ public class BubbleSort {
void bubbleSort(Integer[] arr) {
int n = arr.length;
IntStream.range(0, n - 1)
.flatMap(i -> IntStream.range(i + 1, n - i))
.flatMap(i -> IntStream.range(1, n - i))
.forEach(j -> {
if (arr[j - 1] > arr[j]) {
int temp = arr[j];

View File

@ -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());
}
}

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -98,7 +98,7 @@ public class FindKthLargest {
private int randomPartition(Integer arr[], int left, int right) {
int n = right - left + 1;
int pivot = (int) (Math.random()) % n;
int pivot = (int) (Math.random() * n);
swap(arr, left + pivot, right);
return partition(arr, left, right);
}

View File

@ -1,8 +1,8 @@
package com.baeldung.algorithms.bubblesort;
import static org.junit.Assert.*;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import org.junit.Test;
import org.junit.jupiter.api.Test;
public class BubbleSortUnitTest {

View File

@ -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 };
}
}

View File

@ -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));
}
}

View File

@ -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);
}
}

3
apache-geode/README.md Normal file
View File

@ -0,0 +1,3 @@
### Relevant Articles:
- [A Quick Guide to Apache Geode](https://www.baeldung.com/apache-geode)

8
apache-pulsar/.gitignore vendored Executable file
View File

@ -0,0 +1,8 @@
.classpath
.project
.settings
target
.idea
*.iml
.gradle/
build/

21
apache-pulsar/pom.xml Normal file
View File

@ -0,0 +1,21 @@
<?xml version="1.0" encoding="UTF-8"?>
<project 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">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung.pulsar</groupId>
<artifactId>pulsar-java</artifactId>
<version>0.0.1</version>
<dependencies>
<dependency>
<groupId>org.apache.pulsar</groupId>
<artifactId>pulsar-client</artifactId>
<version>2.1.1-incubating</version>
<scope>compile</scope>
</dependency>
</dependencies>
<properties>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source>
</properties>
</project>

View File

@ -0,0 +1,48 @@
package com.baeldung;
import java.io.IOException;
import org.apache.pulsar.client.api.Consumer;
import org.apache.pulsar.client.api.Message;
import org.apache.pulsar.client.api.PulsarClient;
import org.apache.pulsar.client.api.SubscriptionType;
public class ConsumerTest {
private static final String SERVICE_URL = "pulsar://localhost:6650";
private static final String TOPIC_NAME = "test-topic";
private static final String SUBSCRIPTION_NAME = "test-subscription";
public static void main(String[] args) throws IOException {
// Create a Pulsar client instance. A single instance can be shared across many
// producers and consumer within the same application
PulsarClient client = PulsarClient.builder()
.serviceUrl(SERVICE_URL)
.build();
//Configure consumer specific settings.
Consumer<byte[]> consumer = client.newConsumer()
.topic(TOPIC_NAME)
// Allow multiple consumers to attach to the same subscription
// and get messages dispatched as a queue
.subscriptionType(SubscriptionType.Shared)
.subscriptionName(SUBSCRIPTION_NAME)
.subscribe();
// Once the consumer is created, it can be used for the entire application lifecycle
System.out.println("Created consumer for the topic "+ TOPIC_NAME);
do {
// Wait until a message is available
Message<byte[]> msg = consumer.receive();
// Extract the message as a printable string and then log
String content = new String(msg.getData());
System.out.println("Received message '"+content+"' with ID "+msg.getMessageId());
// Acknowledge processing of the message so that it can be deleted
consumer.acknowledge(msg);
} while (true);
}
}

View File

@ -0,0 +1,58 @@
package com.baeldung;
import org.apache.pulsar.client.api.CompressionType;
import org.apache.pulsar.client.api.Message;
import org.apache.pulsar.client.api.MessageBuilder;
import org.apache.pulsar.client.api.MessageId;
import org.apache.pulsar.client.api.Producer;
import org.apache.pulsar.client.api.PulsarClient;
import org.apache.pulsar.client.api.PulsarClientException;
import java.io.IOException;
import java.util.stream.IntStream;
public class ProducerTest {
private static final String SERVICE_URL = "pulsar://localhost:6650";
private static final String TOPIC_NAME = "test-topic";
public static void main(String[] args) throws IOException {
// Create a Pulsar client instance. A single instance can be shared across many
// producers and consumer within the same application
PulsarClient client = PulsarClient.builder()
.serviceUrl(SERVICE_URL)
.build();
// Configure producer specific settings
Producer<byte[]> producer = client.newProducer()
// Set the topic
.topic(TOPIC_NAME)
// Enable compression
.compressionType(CompressionType.LZ4)
.create();
// Once the producer is created, it can be used for the entire application life-cycle
System.out.println("Created producer for the topic "+TOPIC_NAME);
// Send 5 test messages
IntStream.range(1, 5).forEach(i -> {
String content = String.format("hi-pulsar-%d", i);
// Build a message object
Message<byte[]> msg = MessageBuilder.create()
.setContent(content.getBytes())
.build();
// Send each message and log message content and ID when successfully received
try {
MessageId msgId = producer.send(msg);
System.out.println("Published message '"+content+"' with the ID "+msgId);
} catch (PulsarClientException e) {
System.out.println(e.getMessage());
}
});
client.close();
}
}

View File

@ -0,0 +1,59 @@
package com.baeldung.subscriptions;
import org.apache.pulsar.client.api.ConsumerBuilder;
import org.apache.pulsar.client.api.Message;
import org.apache.pulsar.client.api.MessageBuilder;
import org.apache.pulsar.client.api.Producer;
import org.apache.pulsar.client.api.PulsarClient;
import org.apache.pulsar.client.api.PulsarClientException;
import org.apache.pulsar.client.api.SubscriptionType;
import java.util.stream.IntStream;
public class ExclusiveSubscriptionTest {
private static final String SERVICE_URL = "pulsar://localhost:6650";
private static final String TOPIC_NAME = "test-topic";
private static final String SUBSCRIPTION_NAME = "test-subscription";
private static final SubscriptionType SUBSCRIPTION_TYPE = SubscriptionType.Exclusive;
public static void main(String[] args) throws PulsarClientException {
PulsarClient client = PulsarClient.builder()
.serviceUrl(SERVICE_URL)
.build();
Producer<byte[]> producer = client.newProducer()
.topic(TOPIC_NAME)
.create();
ConsumerBuilder<byte[]> consumer1 = client.newConsumer()
.topic(TOPIC_NAME)
.subscriptionName(SUBSCRIPTION_NAME)
.subscriptionType(SUBSCRIPTION_TYPE);
ConsumerBuilder<byte[]> consumer2 = client.newConsumer()
.topic(TOPIC_NAME)
.subscriptionName(SUBSCRIPTION_NAME)
.subscriptionType(SUBSCRIPTION_TYPE);
IntStream.range(0, 999).forEach(i -> {
Message<byte[]> msg = MessageBuilder.create()
.setContent(String.format("message-%d", i).getBytes())
.build();
try {
producer.send(msg);
} catch (PulsarClientException e) {
System.out.println(e.getMessage());
}
});
// Consumer 1 can subscribe to the topic
consumer1.subscribe();
// Consumer 2 cannot due to the exclusive subscription held by consumer 1
consumer2.subscribeAsync()
.handle((consumer, exception) -> {
System.out.println(exception.getMessage());
return null;
});
}
}

View File

@ -0,0 +1,76 @@
package com.baeldung.subscriptions;
import org.apache.pulsar.client.api.Consumer;
import org.apache.pulsar.client.api.ConsumerBuilder;
import org.apache.pulsar.client.api.Message;
import org.apache.pulsar.client.api.MessageBuilder;
import org.apache.pulsar.client.api.Producer;
import org.apache.pulsar.client.api.PulsarClient;
import org.apache.pulsar.client.api.PulsarClientException;
import org.apache.pulsar.client.api.SubscriptionType;
import java.util.stream.IntStream;
public class FailoverSubscriptionTest {
private static final String SERVICE_URL = "pulsar://localhost:6650";
private static final String TOPIC_NAME = "failover-subscription-test-topic";
private static final String SUBSCRIPTION_NAME = "test-subscription";
private static final SubscriptionType SUBSCRIPTION_TYPE = SubscriptionType.Failover;
private static final int NUM_MSGS = 10;
public static void main(String[] args) throws PulsarClientException {
PulsarClient client = PulsarClient.builder()
.serviceUrl(SERVICE_URL)
.build();
Producer<byte[]> producer = client.newProducer()
.topic(TOPIC_NAME)
.create();
ConsumerBuilder<byte[]> consumerBuilder = client.newConsumer()
.topic(TOPIC_NAME)
.subscriptionName(SUBSCRIPTION_NAME)
.subscriptionType(SUBSCRIPTION_TYPE);
Consumer<byte[]> mainConsumer = consumerBuilder
.consumerName("consumer-a")
.messageListener((consumer, msg) -> {
System.out.println("Message received by main consumer");
try {
consumer.acknowledge(msg);
} catch (PulsarClientException e) {
System.out.println(e.getMessage());
}
})
.subscribe();
Consumer<byte[]> failoverConsumer = consumerBuilder
.consumerName("consumer-b")
.messageListener((consumer, msg) -> {
System.out.println("Message received by failover consumer");
try {
consumer.acknowledge(msg);
} catch (PulsarClientException e) {
System.out.println(e.getMessage());
}
})
.subscribe();
IntStream.range(0, NUM_MSGS).forEach(i -> {
Message<byte[]> msg = MessageBuilder.create()
.setContent(String.format("message-%d", i).getBytes())
.build();
try {
producer.send(msg);
Thread.sleep(100);
if (i > 5) mainConsumer.close();
} catch (InterruptedException | PulsarClientException e) {
System.out.println(e.getMessage());
}
});
}
}

View File

@ -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)

View File

@ -32,3 +32,4 @@
- [Set the Time Zone of a Date in Java](https://www.baeldung.com/java-set-date-time-zone)
- [An Overview of Regular Expressions Performance in Java](https://www.baeldung.com/java-regex-performance)
- [Java Primitives versus Objects](https://www.baeldung.com/java-primitives-vs-objects)
- [How to Use if/else Logic in Java 8 Streams](https://www.baeldung.com/java-8-streams-if-else-logic)

View File

@ -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);
}
}

View File

@ -1,16 +1,18 @@
package com.baeldung.java8;
import com.baeldung.java8.entity.Human;
import com.google.common.collect.Lists;
import com.google.common.primitives.Ints;
import org.junit.Assert;
import org.junit.Test;
import static org.hamcrest.Matchers.equalTo;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import static org.hamcrest.Matchers.equalTo;
import org.junit.Assert;
import org.junit.Test;
import com.baeldung.java8.entity.Human;
import com.google.common.collect.Lists;
import com.google.common.primitives.Ints;
public class Java8SortUnitTest {
@ -111,5 +113,22 @@ public class Java8SortUnitTest {
humans.sort(Comparator.comparing(Human::getName));
Assert.assertThat(humans.get(0), equalTo(new Human("Jack", 12)));
}
@Test
public final void givenStreamNaturalOrdering_whenSortingEntitiesByName_thenCorrectlySorted() {
final List<String> letters = Lists.newArrayList("B", "A", "C");
final List<String> sortedLetters = letters.stream().sorted().collect(Collectors.toList());
Assert.assertThat(sortedLetters.get(0), equalTo("A"));
}
@Test
public final void givenStreamCustomOrdering_whenSortingEntitiesByName_thenCorrectlySorted() {
final List<Human> humans = Lists.newArrayList(new Human("Sarah", 10), new Human("Jack", 12));
final Comparator<Human> nameComparator = (h1, h2) -> h1.getName().compareTo(h2.getName());
final List<Human> sortedHumans = humans.stream().sorted(nameComparator).collect(Collectors.toList());
Assert.assertThat(sortedHumans.get(0), equalTo(new Human("Jack", 12)));
}
}

View File

@ -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)

View File

@ -4,37 +4,23 @@
### Relevant Articles:
- [Immutable ArrayList in Java](http://www.baeldung.com/java-immutable-list)
- [Converting between an Array and a List in Java](http://www.baeldung.com/convert-array-to-list-and-list-to-array)
- [Converting between an Array and a Set in Java](http://www.baeldung.com/convert-array-to-set-and-set-to-array)
- [Converting between a List and a Set in Java](http://www.baeldung.com/convert-list-to-set-and-set-to-list)
- [Convert a Map to an Array, List or Set in Java](http://www.baeldung.com/convert-map-values-to-array-list-set)
- [Guide to the Java ArrayList](http://www.baeldung.com/java-arraylist)
- [Random List Element](http://www.baeldung.com/java-random-list-element)
- [Java - Combine Multiple Collections](http://www.baeldung.com/java-combine-multiple-collections)
- [Guide to WeakHashMap in Java](http://www.baeldung.com/java-weakhashmap)
- [Guide to the Guava BiMap](http://www.baeldung.com/guava-bimap)
- [The Java HashMap Under the Hood](http://www.baeldung.com/java-hashmap)
- [A Guide to LinkedHashMap in Java](http://www.baeldung.com/java-linked-hashmap)
- [A Guide to TreeMap in Java](http://www.baeldung.com/java-treemap)
- [Removing all nulls from a List in Java](http://www.baeldung.com/java-remove-nulls-from-list)
- [Removing all duplicates from a List in Java](http://www.baeldung.com/java-remove-duplicates-from-list)
- [Flattening Nested Collections in Java](http://www.baeldung.com/java-flatten-nested-collections)
- [HashSet and TreeSet Comparison](http://www.baeldung.com/java-hashset-vs-treeset)
- [Iterate over a Map in Java](http://www.baeldung.com/java-iterate-map)
- [Collect a Java Stream to an Immutable Collection](http://www.baeldung.com/java-stream-immutable-collection)
- [Converting a List to String in Java](http://www.baeldung.com/java-list-to-string)
- [Introduction to the Java ArrayDeque](http://www.baeldung.com/java-array-deque)
- [A Guide to HashSet in Java](http://www.baeldung.com/java-hashset)
- [A Guide to TreeSet in Java](http://www.baeldung.com/java-tree-set)
- [Java TreeMap vs HashMap](http://www.baeldung.com/java-treemap-vs-hashmap)
- [How to TDD a List Implementation in Java](http://www.baeldung.com/java-test-driven-list)
- [How to Store Duplicate Keys in a Map in Java?](http://www.baeldung.com/java-map-duplicate-keys)
- [Getting the Size of an Iterable in Java](http://www.baeldung.com/java-iterable-size)
- [Iterating Backward Through a List](http://www.baeldung.com/java-list-iterate-backwards)
- [How to Filter a Collection in Java](http://www.baeldung.com/java-collection-filtering)
- [Add Multiple Items to an Java ArrayList](http://www.baeldung.com/java-add-items-array-list)
- [Remove the First Element from a List](http://www.baeldung.com/java-remove-first-element-from-list)
- [How to Convert List to Map in Java](http://www.baeldung.com/java-list-to-map)
- [Initializing HashSet at the Time of Construction](http://www.baeldung.com/java-initialize-hashset)
- [Removing the First Element of an Array](https://www.baeldung.com/java-array-remove-first-element)
- [Fail-Safe Iterator vs Fail-Fast Iterator](http://www.baeldung.com/java-fail-safe-vs-fail-fast-iterator)
@ -47,7 +33,9 @@
- [Remove All Occurrences of a Specific Value from a List](https://www.baeldung.com/java-remove-value-from-list)
- [Thread Safe LIFO Data Structure Implementations](https://www.baeldung.com/java-lifo-thread-safe)
- [Collections.emptyList() vs. New List Instance](https://www.baeldung.com/java-collections-emptylist-new-list)
- [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap)
- [Differences Between Collection.clear() and Collection.removeAll()](https://www.baeldung.com/java-collection-clear-vs-removeall)
- [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)
- [Operating on and Removing an Item from Stream](https://www.baeldung.com/java-use-remove-item-stream)
- [An Introduction to Synchronized Java Collections](https://www.baeldung.com/java-synchronized-collections)
- [Guide to EnumSet](https://www.baeldung.com/java-enumset)

View File

@ -1,85 +1,71 @@
<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>
</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>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>${commons-collections4.version}</version>
</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>
</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>

View File

@ -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);
}
}

View File

@ -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));
}
}

View File

@ -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));
}
}

View File

@ -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));
}
}

View File

@ -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);
}
}

View File

@ -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());});
}
}
}

View File

@ -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;
}
}

View File

@ -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));
}
}

View File

@ -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);
}
}

View File

@ -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");
}
}

View File

@ -0,0 +1,30 @@
package com.baeldung.synchronizedcollections.test;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import static org.assertj.core.api.Assertions.*;
public class SynchronizedMapUnitTest {
@Test
public void givenSynchronizedMap_whenTwoThreadsAddElements_thenCorrectMapSize() throws InterruptedException {
Map<Integer, String> syncMap = Collections.synchronizedMap(new HashMap<>());
Runnable mapOperations = () -> {
syncMap.put(1, "one");
syncMap.put(2, "two");
syncMap.put(3, "three");
};
Thread thread1 = new Thread(mapOperations);
Thread thread2 = new Thread(mapOperations);
thread1.start();
thread2.start();
thread1.join();
thread2.join();
assertThat(syncMap.size()).isEqualTo(3);
}
}

View File

@ -0,0 +1,26 @@
package com.baeldung.synchronizedcollections.test;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import org.junit.Test;
import static org.assertj.core.api.Assertions.*;
public class SynchronizedSetUnitTest {
@Test
public void givenSynchronizedSet_whenTwoThreadsAddElements_thenCorrectSetSize() throws InterruptedException {
Set<Integer> syncSet = Collections.synchronizedSet(new HashSet<>());
Runnable setOperations = () -> {syncSet.addAll(Arrays.asList(1, 2, 3, 4, 5, 6));};
Thread thread1 = new Thread(setOperations);
Thread thread2 = new Thread(setOperations);
thread1.start();
thread2.start();
thread1.join();
thread2.join();
assertThat(syncSet.size()).isEqualTo(6);
}
}

View File

@ -0,0 +1,29 @@
package com.baeldung.synchronizedcollections.test;
import java.util.Collections;
import java.util.Map;
import java.util.TreeMap;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
public class SynchronizedSortedMapUnitTest {
@Test
public void givenSynchronizedSorteMap_whenTwoThreadsAddElements_thenCorrectSortedMapSize() throws InterruptedException {
Map<Integer, String> syncSortedMap = Collections.synchronizedSortedMap(new TreeMap<>());
Runnable sortedMapOperations = () -> {
syncSortedMap.put(1, "One");
syncSortedMap.put(2, "Two");
syncSortedMap.put(3, "Three");
};
Thread thread1 = new Thread(sortedMapOperations);
Thread thread2 = new Thread(sortedMapOperations);
thread1.start();
thread2.start();
thread1.join();
thread2.join();
assertThat(syncSortedMap.size()).isEqualTo(3);
}
}

View File

@ -0,0 +1,28 @@
package com.baeldung.synchronizedcollections.test;
import java.util.Arrays;
import java.util.Collections;
import java.util.SortedSet;
import java.util.TreeSet;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
public class SynchronizedSortedSetUnitTest {
@Test
public void givenSynchronizedSortedSet_whenTwoThreadsAddElements_thenCorrectSortedSetSize() throws InterruptedException {
SortedSet<Integer> syncSortedSet = Collections.synchronizedSortedSet(new TreeSet<>());
Runnable sortedSetOperations = () -> {syncSortedSet.addAll(Arrays.asList(1, 2, 3, 4, 5, 6));};
sortedSetOperations.run();
sortedSetOperations.run();
Thread thread1 = new Thread(sortedSetOperations);
Thread thread2 = new Thread(sortedSetOperations);
thread1.start();
thread2.start();
thread1.join();
thread2.join();
assertThat(syncSortedSet.size()).isEqualTo(6);
}
}

View File

@ -29,3 +29,4 @@
- [A Custom Spring SecurityConfigurer](http://www.baeldung.com/spring-security-custom-configurer)
- [Life Cycle of a Thread in Java](http://www.baeldung.com/java-thread-lifecycle)
- [Runnable vs. Callable in Java](http://www.baeldung.com/java-runnable-callable)
- [Brief Introduction to Java Thread.yield()](https://www.baeldung.com/java-thread-yield)

View File

@ -184,5 +184,25 @@ public class CompletableFutureLongRunningUnitTest {
assertEquals("Hello World", future.get());
}
@Test
public void whenPassingTransformation_thenFunctionExecutionWithThenApply() throws InterruptedException, ExecutionException {
CompletableFuture<Integer> finalResult = compute().thenApply(s -> s + 1);
assertTrue(finalResult.get() == 11);
}
@Test
public void whenPassingPreviousStage_thenFunctionExecutionWithThenCompose() throws InterruptedException, ExecutionException {
CompletableFuture<Integer> finalResult = compute().thenCompose(this::computeAnother);
assertTrue(finalResult.get() == 20);
}
public CompletableFuture<Integer> compute(){
return CompletableFuture.supplyAsync(() -> 10);
}
public CompletableFuture<Integer> computeAnother(Integer i){
return CompletableFuture.supplyAsync(() -> 10 + i);
}
}

View File

@ -31,4 +31,5 @@
- [Create a Symbolic Link with Java](http://www.baeldung.com/java-symlink)
- [Quick Use of FilenameFilter](http://www.baeldung.com/java-filename-filter)
- [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap)
- [ Read a File into an ArrayList](https://www.baeldung.com/java-file-to-arraylist)
- [Read a File into an ArrayList](https://www.baeldung.com/java-file-to-arraylist)
- [Guide to Java OutputStream](https://www.baeldung.com/java-outputstream)

View File

@ -154,6 +154,12 @@
<artifactId>async-http-client</artifactId>
<version>${async-http-client.version}</version>
</dependency>
<dependency>
<groupId>com.opencsv</groupId>
<artifactId>opencsv</artifactId>
<version>${opencsv.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
@ -247,7 +253,7 @@
<protonpack.version>1.13</protonpack.version>
<streamex.version>0.6.5</streamex.version>
<vavr.version>0.9.0</vavr.version>
<opencsv.version>4.1</opencsv.version>
<!-- testing -->
<assertj.version>3.6.1</assertj.version>
<avaitility.version>1.7.0</avaitility.version>

View File

@ -0,0 +1,48 @@
package com.baeldung.stream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
public class OutputStreamExamples {
public void fileOutputStreamByteSequence(String file, String data) throws IOException {
byte[] bytes = data.getBytes();
try (OutputStream out = new FileOutputStream(file)) {
out.write(bytes);
}
}
public void fileOutputStreamByteSubSequence(String file, String data) throws IOException {
byte[] bytes = data.getBytes();
try (OutputStream out = new FileOutputStream(file)) {
out.write(bytes, 6, 5);
}
}
public void fileOutputStreamByteSingle(String file, String data) throws IOException {
byte[] bytes = data.getBytes();
try (OutputStream out = new FileOutputStream(file)) {
out.write(bytes[6]);
}
}
public void bufferedOutputStream(String file, String... data) throws IOException {
try (BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file))) {
for (String s : data) {
out.write(s.getBytes());
out.write(" ".getBytes());
}
}
}
public void outputStreamWriter(String file, String data) throws IOException {
try (OutputStream out = new FileOutputStream(file); Writer writer = new OutputStreamWriter(out, "UTF-8")) {
writer.write(data);
}
}
}

View File

@ -0,0 +1 @@
Test1

View File

@ -0,0 +1 @@
Test2

View File

@ -0,0 +1,106 @@
package com.baeldung.csv;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
import org.junit.Assert;
import org.junit.Test;
import com.opencsv.CSVReader;
public class ReadCSVInArrayUnitTest {
public static final String COMMA_DELIMITER = ",";
public static final String CSV_FILE = "src/test/resources/book.csv";
public static final List<List<String>> EXPECTED_ARRAY = Collections.unmodifiableList(new ArrayList<List<String>>() {
{
add(new ArrayList<String>() {
{
add("Mary Kom");
add("Unbreakable");
}
});
add(new ArrayList<String>() {
{
add("Kapil Isapuari");
add("Farishta");
}
});
}
});
@Test
public void givenCSVFile_whenBufferedReader_thenContentsAsExpected() throws IOException {
List<List<String>> records = new ArrayList<List<String>>();
try (BufferedReader br = new BufferedReader(new FileReader(CSV_FILE))) {
String line = "";
while ((line = br.readLine()) != null) {
String[] values = line.split(COMMA_DELIMITER);
records.add(Arrays.asList(values));
}
} catch (Exception e) {
e.printStackTrace();
}
for (int i = 0; i < EXPECTED_ARRAY.size(); i++) {
Assert.assertArrayEquals(EXPECTED_ARRAY.get(i)
.toArray(),
records.get(i)
.toArray());
}
}
@Test
public void givenCSVFile_whenScanner_thenContentsAsExpected() throws IOException {
List<List<String>> records = new ArrayList<List<String>>();
try (Scanner scanner = new Scanner(new File(CSV_FILE));) {
while (scanner.hasNextLine()) {
records.add(getRecordFromLine(scanner.nextLine()));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
for (int i = 0; i < EXPECTED_ARRAY.size(); i++) {
Assert.assertArrayEquals(EXPECTED_ARRAY.get(i)
.toArray(),
records.get(i)
.toArray());
}
}
private List<String> getRecordFromLine(String line) {
List<String> values = new ArrayList<String>();
try (Scanner rowScanner = new Scanner(line)) {
rowScanner.useDelimiter(COMMA_DELIMITER);
while (rowScanner.hasNext()) {
values.add(rowScanner.next());
}
}
return values;
}
@Test
public void givenCSVFile_whenOpencsv_thenContentsAsExpected() throws IOException {
List<List<String>> records = new ArrayList<List<String>>();
try (CSVReader csvReader = new CSVReader(new FileReader(CSV_FILE));) {
String[] values = null;
while ((values = csvReader.readNext()) != null) {
records.add(Arrays.asList(values));
}
} catch (Exception e) {
e.printStackTrace();
}
for (int i = 0; i < EXPECTED_ARRAY.size(); i++) {
Assert.assertArrayEquals(EXPECTED_ARRAY.get(i)
.toArray(),
records.get(i)
.toArray());
}
}
}

View File

@ -0,0 +1,76 @@
package com.baeldung.stream;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import org.junit.Before;
import org.junit.Test;
public class OutputStreamExamplesUnitTest {
StringBuilder filePath = new StringBuilder();
@Before
public void init() {
filePath.append("src");
filePath.append(File.separator);
filePath.append("test");
filePath.append(File.separator);
filePath.append("resources");
filePath.append(File.separator);
filePath.append("output_file.txt");
}
@Test
public void givenOutputStream_whenWriteSingleByteCalled_thenOutputCreated() throws IOException {
final File file = new File(filePath.toString());
OutputStreamExamples examples = new OutputStreamExamples();
examples.fileOutputStreamByteSingle(filePath.toString(), "Hello World!");
assertTrue(file.exists());
file.delete();
}
@Test
public void givenOutputStream_whenWriteByteSequenceCalled_thenOutputCreated() throws IOException {
final File file = new File(filePath.toString());
OutputStreamExamples examples = new OutputStreamExamples();
examples.fileOutputStreamByteSequence(filePath.toString(), "Hello World!");
assertTrue(file.exists());
file.delete();
}
@Test
public void givenOutputStream_whenWriteByteSubSequenceCalled_thenOutputCreated() throws IOException {
final File file = new File(filePath.toString());
OutputStreamExamples examples = new OutputStreamExamples();
examples.fileOutputStreamByteSubSequence(filePath.toString(), "Hello World!");
assertTrue(file.exists());
file.delete();
}
@Test
public void givenBufferedOutputStream_whenCalled_thenOutputCreated() throws IOException {
final File file = new File(filePath.toString());
OutputStreamExamples examples = new OutputStreamExamples();
examples.bufferedOutputStream(filePath.toString(), "Hello", "World!");
assertTrue(file.exists());
file.delete();
}
@Test
public void givenOutputStreamWriter_whenCalled_thenOutputCreated() throws IOException {
final File file = new File(filePath.toString());
OutputStreamExamples examples = new OutputStreamExamples();
examples.outputStreamWriter(filePath.toString(), "Hello World!");
assertTrue(file.exists());
file.delete();
}
}

View File

@ -0,0 +1,2 @@
Mary Kom,Unbreakable
Kapil Isapuari,Farishta
1 Mary Kom Unbreakable
2 Kapil Isapuari Farishta

View File

@ -25,19 +25,16 @@
- [The Traveling Salesman Problem in Java](http://www.baeldung.com/java-simulated-annealing-for-traveling-salesman)
- [How to Create an Executable JAR with Maven](http://www.baeldung.com/executable-jar-with-maven)
- [How to Design a Genetic Algorithm in Java](http://www.baeldung.com/java-genetic-algorithm)
- [Spring Security Cache Control Headers](http://www.baeldung.com/spring-security-cache-control-headers)
- [Basic Introduction to JMX](http://www.baeldung.com/java-management-extensions)
- [AWS Lambda With Java](http://www.baeldung.com/java-aws-lambda)
- [Introduction to Nashorn](http://www.baeldung.com/java-nashorn)
- [Chained Exceptions in Java](http://www.baeldung.com/java-chained-exceptions)
- [A Quick JUnit vs TestNG Comparison](http://www.baeldung.com/junit-vs-testng)
- [Java Primitive Conversions](http://www.baeldung.com/java-primitive-conversions)
- [Java Money and the Currency API](http://www.baeldung.com/java-money-and-currency)
- [JVM Log Forging](http://www.baeldung.com/jvm-log-forging)
- [Guide to sun.misc.Unsafe](http://www.baeldung.com/java-unsafe)
- [How to Perform a Simple HTTP Request in Java](http://www.baeldung.com/java-http-request)
- [Call Methods at Runtime Using Java Reflection](http://www.baeldung.com/java-method-reflection)
- [Guide to UUID in JAVA](http://www.baeldung.com/guide-to-uuid-in-java)
- [How to Add a Single Element to a Stream](http://www.baeldung.com/java-stream-append-prepend)
- [Iterating Over Enum Values in Java](http://www.baeldung.com/java-enum-iteration)
- [Kotlin Java Interoperability](http://www.baeldung.com/kotlin-java-interoperability)
@ -152,3 +149,12 @@
- [Throw Exception in Optional in Java 8](https://www.baeldung.com/java-optional-throw-exception)
- [Add a Character to a String at a Given Position](https://www.baeldung.com/java-add-character-to-string)
- [Synthetic Constructs in Java](https://www.baeldung.com/java-synthetic)
- [Calculating the nth Root in Java](https://www.baeldung.com/java-nth-root)
- [Convert Double to String, Removing Decimal Places](https://www.baeldung.com/java-double-to-string)
- [Different Ways to Capture Java Heap Dumps](https://www.baeldung.com/java-heap-dump-capture)
- [How to Separate Double into Integer and Decimal Parts](https://www.baeldung.com/java-separate-double-into-integer-decimal-parts)
- [ZoneOffset in Java](https://www.baeldung.com/java-zone-offset)
- [Hashing a Password in Java](https://www.baeldung.com/java-password-hashing)
- [Java Switch Statement](https://www.baeldung.com/java-switch)
- [The Modulo Operator in Java](https://www.baeldung.com/modulo-java)
- [Ternary Operator In Java](https://www.baeldung.com/java-ternary-operator)

View File

@ -0,0 +1,159 @@
package com.baeldung.array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class ArrayReferenceGuide {
public static void main(String[] args) {
declaration();
initialization();
access();
iterating();
varargs();
transformIntoList();
transformIntoStream();
sort();
search();
merge();
}
private static void declaration() {
int[] anArray;
int anotherArray[];
}
private static void initialization() {
int[] anArray = new int[10];
anArray[0] = 10;
anArray[5] = 4;
int[] anotherArray = new int[] {1, 2, 3, 4, 5};
}
private static void access() {
int[] anArray = new int[10];
anArray[0] = 10;
anArray[5] = 4;
System.out.println(anArray[0]);
}
private static void iterating() {
int[] anArray = new int[] {1, 2, 3, 4, 5};
for (int i = 0; i < anArray.length; i++) {
System.out.println(anArray[i]);
}
for (int element : anArray) {
System.out.println(element);
}
}
private static void varargs() {
String[] groceries = new String[] {"Milk", "Tomato", "Chips"};
varargMethod(groceries);
varargMethod("Milk", "Tomato", "Chips");
}
private static void varargMethod(String... varargs) {
for (String element : varargs) {
System.out.println(element);
}
}
private static void transformIntoList() {
Integer[] anArray = new Integer[] {1, 2, 3, 4, 5};
// Naïve implementation
List<Integer> aList = new ArrayList<>(); // We create an empty list
for (int element : anArray) {
// We iterate over array's elements and add them to the list
aList.add(element);
}
// Pretty implementation
aList = Arrays.asList(anArray);
// Drawbacks
try {
aList.remove(0);
} catch (UnsupportedOperationException e) {
System.out.println(e.getMessage());
}
try {
aList.add(6);
} catch (UnsupportedOperationException e) {
System.out.println(e.getMessage());
}
int[] anotherArray = new int[] {1, 2, 3, 4, 5};
// List<Integer> anotherList = Arrays.asList(anotherArray);
}
private static void transformIntoStream() {
int[] anArray = new int[] {1, 2, 3, 4, 5};
IntStream aStream = Arrays.stream(anArray);
Integer[] anotherArray = new Integer[] {1, 2, 3, 4, 5};
Stream<Integer> anotherStream = Arrays.stream(anotherArray, 2, 4);
}
private static void sort() {
int[] anArray = new int[] {5, 2, 1, 4, 8};
Arrays.sort(anArray); // anArray is now {1, 2, 4, 5, 8}
Integer[] anotherArray = new Integer[] {5, 2, 1, 4, 8};
Arrays.sort(anotherArray); // anArray is now {1, 2, 4, 5, 8}
String[] yetAnotherArray = new String[] {"A", "E", "Z", "B", "C"};
Arrays.sort(yetAnotherArray, 1, 3, Comparator.comparing(String::toString).reversed()); // yetAnotherArray is now {"A", "Z", "E", "B", "C"}
}
private static void search() {
int[] anArray = new int[] {5, 2, 1, 4, 8};
for (int i = 0; i < anArray.length; i++) {
if (anArray[i] == 4) {
System.out.println("Found at index " + i);
break;
}
}
Arrays.sort(anArray);
int index = Arrays.binarySearch(anArray, 4);
System.out.println("Found at index " + index);
}
private static void merge() {
int[] anArray = new int[] {5, 2, 1, 4, 8};
int[] anotherArray = new int[] {10, 4, 9, 11, 2};
int[] resultArray = new int[anArray.length + anotherArray.length];
for (int i = 0; i < resultArray.length; i++) {
resultArray[i] = (i < anArray.length ? anArray[i] : anotherArray[i - anArray.length]);
}
for (int element : resultArray) {
System.out.println(element);
}
Arrays.setAll(resultArray, i -> (i < anArray.length ? anArray[i] : anotherArray[i - anArray.length]));
for (int element : resultArray) {
System.out.println(element);
}
}
}

View File

@ -1,11 +1,14 @@
package com.baeldung.classloader;
import java.io.*;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
public class CustomClassLoader extends ClassLoader {
public Class getClass(String name) throws ClassNotFoundException {
@Override
public Class findClass(String name) throws ClassNotFoundException {
byte[] b = loadClassFromFile(name);
return defineClass(name, b, 0, b.length);
}

View File

@ -0,0 +1,41 @@
package com.baeldung.string;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.NumberFormat;
public class DoubleToString {
public static String truncateByCast(double d) {
return String.valueOf((int) d);
}
public static String roundWithStringFormat(double d) {
return String.format("%.0f", d);
}
public static String truncateWithNumberFormat(double d) {
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(0);
nf.setRoundingMode(RoundingMode.FLOOR);
return nf.format(d);
}
public static String roundWithNumberFormat(double d) {
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(0);
return nf.format(d);
}
public static String truncateWithDecimalFormat(double d) {
DecimalFormat df = new DecimalFormat("#,###");
df.setRoundingMode(RoundingMode.FLOOR);
return df.format(d);
}
public static String roundWithDecimalFormat(double d) {
DecimalFormat df = new DecimalFormat("#,###");
return df.format(d);
}
}

View File

@ -11,7 +11,7 @@ public class CustomClassLoaderUnitTest {
public void customLoader() throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
CustomClassLoader customClassLoader = new CustomClassLoader();
Class<?> c = customClassLoader.getClass(PrintClassLoader.class.getName());
Class<?> c = customClassLoader.findClass(PrintClassLoader.class.getName());
Object ob = c.newInstance();

View File

@ -0,0 +1,54 @@
package com.baeldung.modulo;
import org.junit.Test;
import static org.assertj.core.api.Java6Assertions.*;
public class ModuloUnitTest {
@Test
public void whenIntegerDivision_thenLosesRemainder(){
assertThat(11 / 4).isEqualTo(2);
}
@Test
public void whenDoubleDivision_thenKeepsRemainder(){
assertThat(11 / 4.0).isEqualTo(2.75);
}
@Test
public void whenModulo_thenReturnsRemainder(){
assertThat(11 % 4).isEqualTo(3);
}
@Test(expected = ArithmeticException.class)
public void whenDivisionByZero_thenArithmeticException(){
double result = 1 / 0;
}
@Test(expected = ArithmeticException.class)
public void whenModuloByZero_thenArithmeticException(){
double result = 1 % 0;
}
@Test
public void whenDivisorIsOddAndModulusIs2_thenResultIs1(){
assertThat(3 % 2).isEqualTo(1);
}
@Test
public void whenDivisorIsEvenAndModulusIs2_thenResultIs0(){
assertThat(4 % 2).isEqualTo(0);
}
@Test
public void whenItemsIsAddedToCircularQueue_thenNoArrayIndexOutOfBounds(){
int QUEUE_CAPACITY= 10;
int[] circularQueue = new int[QUEUE_CAPACITY];
int itemsInserted = 0;
for (int value = 0; value < 1000; value++) {
int writeIndex = ++itemsInserted % QUEUE_CAPACITY;
circularQueue[writeIndex] = value;
}
}
}

View File

@ -1,11 +1,11 @@
package com.baeldung.nth.root.calculator;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.runners.MockitoJUnitRunner;
import static org.junit.Assert.assertEquals;
import org.mockito.junit.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class NthRootCalculatorUnitTest {

View File

@ -0,0 +1,59 @@
package com.baeldung;
import org.junit.Test;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import java.util.logging.Logger;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class SimpleDateFormatUnitTest {
private static final Logger logger = Logger.getLogger(SimpleDateFormatUnitTest.class.getName());
@Test
public void givenSpecificDate_whenFormatted_thenCheckFormatCorrect() throws Exception {
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
assertEquals("24-05-1977", formatter.format(new Date(233345223232L)));
}
@Test
public void givenSpecificDate_whenFormattedUsingDateFormat_thenCheckFormatCorrect() throws Exception {
DateFormat formatter = DateFormat.getDateInstance(DateFormat.SHORT);
assertEquals("5/24/77", formatter.format(new Date(233345223232L)));
}
@Test
public void givenStringDate_whenParsed_thenCheckDateCorrect() throws Exception{
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
Date myDate = new Date(233276400000L);
Date parsedDate = formatter.parse("24-05-1977");
assertEquals(myDate.getTime(), parsedDate.getTime());
}
@Test
public void givenFranceLocale_whenFormatted_thenCheckFormatCorrect() throws Exception{
SimpleDateFormat franceDateFormatter = new SimpleDateFormat("EEEEE dd-MMMMMMM-yyyy", Locale.FRANCE);
Date myWednesday = new Date(1539341312904L);
assertTrue(franceDateFormatter.format(myWednesday).startsWith("vendredi"));
}
@Test
public void given2TimeZones_whenFormatted_thenCheckTimeDifference() throws Exception {
Date now = new Date();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEEE dd-MMM-yy HH:mm:ssZ");
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("Europe/London"));
logger.info(simpleDateFormat.format(now));
//change the date format
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("America/New_York"));
logger.info(simpleDateFormat.format(now));
}
}

View File

@ -0,0 +1,45 @@
package com.baeldung.string;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
public class DoubleToStringUnitTest {
private static final double DOUBLE_VALUE = 3.56;
private static final String TRUNCATED_DOUBLE = "3";
private static final String ROUNDED_UP_DOUBLE = "4";
@Test
public void truncateByCastTest() {
assertThat(DoubleToString.truncateByCast(DOUBLE_VALUE)).isEqualTo(TRUNCATED_DOUBLE);
}
@Test
public void roundingWithStringFormatTest() {
assertThat(DoubleToString.roundWithStringFormat(DOUBLE_VALUE)).isEqualTo(ROUNDED_UP_DOUBLE);
}
@Test
public void truncateWithNumberFormatTest() {
assertThat(DoubleToString.truncateWithNumberFormat(DOUBLE_VALUE)).isEqualTo(TRUNCATED_DOUBLE);
}
@Test
public void roundWithNumberFormatTest() {
assertThat(DoubleToString.roundWithNumberFormat(DOUBLE_VALUE)).isEqualTo(ROUNDED_UP_DOUBLE);
}
@Test
public void truncateWithDecimalFormatTest() {
assertThat(DoubleToString.truncateWithDecimalFormat(DOUBLE_VALUE)).isEqualTo(TRUNCATED_DOUBLE);
}
@Test
public void roundWithDecimalFormatTest() {
assertThat(DoubleToString.roundWithDecimalFormat(DOUBLE_VALUE)).isEqualTo(ROUNDED_UP_DOUBLE);
}
}

View File

@ -37,3 +37,6 @@
- [Kotlin with Ktor](https://www.baeldung.com/kotlin-ktor)
- [Fuel HTTP Library with Kotlin](https://www.baeldung.com/kotlin-fuel)
- [Introduction to Kovenant Library for Kotlin](https://www.baeldung.com/kotlin-kovenant)
- [Converting Kotlin Data Class from JSON using GSON](https://www.baeldung.com/kotlin-json-convert-data-class)
- [Concatenate Strings in Kotlin](https://www.baeldung.com/kotlin-concatenate-strings)
- [Kotlin return, break, continue Keywords](https://www.baeldung.com/kotlin-return-break-continue)

View File

@ -0,0 +1,19 @@
package com.baeldung.datastructures
/**
* Example of how to use the {@link Node} class.
*
*/
fun main(args: Array<String>) {
val tree = Node(4)
val keys = arrayOf(8, 15, 21, 3, 7, 2, 5, 10, 2, 3, 4, 6, 11)
for (key in keys) {
tree.insert(key)
}
val node = tree.find(4)!!
println("Node with value ${node.key} [left = ${node.left?.key}, right = ${node.right?.key}]")
println("Delete node with key = 3")
node.delete(3)
print("Tree content after the node elimination: ")
println(tree.visit().joinToString { it.toString() })
}

View File

@ -0,0 +1,167 @@
package com.baeldung.datastructures
/**
* An ADT for a binary search tree.
* Note that this data type is neither immutable nor thread safe.
*/
class Node(
var key: Int,
var left: Node? = null,
var right: Node? = null) {
/**
* Return a node with given value. If no such node exists, return null.
* @param value
*/
fun find(value: Int): Node? = when {
this.key > value -> left?.find(value)
this.key < value -> right?.find(value)
else -> this
}
/**
* Insert a given value into the tree.
* After insertion, the tree should contain a node with the given value.
* If the tree already contains the given value, nothing is performed.
* @param value
*/
fun insert(value: Int) {
if (value > this.key) {
if (this.right == null) {
this.right = Node(value)
} else {
this.right?.insert(value)
}
} else if (value < this.key) {
if (this.left == null) {
this.left = Node(value)
} else {
this.left?.insert(value)
}
}
}
/**
* Delete the value from the given tree. If the tree does not contain the value, the tree remains unchanged.
* @param value
*/
fun delete(value: Int) {
when {
value > key -> scan(value, this.right, this)
value < key -> scan(value, this.left, this)
else -> removeNode(this, null)
}
}
/**
* Scan the tree in the search of the given value.
* @param value
* @param node sub-tree that potentially might contain the sought value
* @param parent node's parent
*/
private fun scan(value: Int, node: Node?, parent: Node?) {
if (node == null) {
System.out.println("value " + value
+ " seems not present in the tree.")
return
}
when {
value > node.key -> scan(value, node.right, node)
value < node.key -> scan(value, node.left, node)
value == node.key -> removeNode(node, parent)
}
}
/**
* Remove the node.
*
* Removal process depends on how many children the node has.
*
* @param node node that is to be removed
* @param parent parent of the node to be removed
*/
private fun removeNode(node: Node, parent: Node?) {
node.left?.let { leftChild ->
run {
node.right?.let {
removeTwoChildNode(node)
} ?: removeSingleChildNode(node, leftChild)
}
} ?: run {
node.right?.let { rightChild -> removeSingleChildNode(node, rightChild) } ?: removeNoChildNode(node, parent)
}
}
/**
* Remove the node without children.
* @param node
* @param parent
*/
private fun removeNoChildNode(node: Node, parent: Node?) {
parent?.let { p ->
if (node == p.left) {
p.left = null
} else if (node == p.right) {
p.right = null
}
} ?: throw IllegalStateException(
"Can not remove the root node without child nodes")
}
/**
* Remove a node that has two children.
*
* The process of elimination is to find the biggest key in the left sub-tree and replace the key of the
* node that is to be deleted with that key.
*/
private fun removeTwoChildNode(node: Node) {
val leftChild = node.left!!
leftChild.right?.let {
val maxParent = findParentOfMaxChild(leftChild)
maxParent.right?.let {
node.key = it.key
maxParent.right = null
} ?: throw IllegalStateException("Node with max child must have the right child!")
} ?: run {
node.key = leftChild.key
node.left = leftChild.left
}
}
/**
* Return a node whose right child contains the biggest value in the given sub-tree.
* Assume that the node n has a non-null right child.
*
* @param n
*/
private fun findParentOfMaxChild(n: Node): Node {
return n.right?.let { r -> r.right?.let { findParentOfMaxChild(r) } ?: n }
?: throw IllegalArgumentException("Right child must be non-null")
}
/**
* Remove a parent that has only one child.
* Removal is effectively is just coping the data from the child parent to the parent parent.
* @param parent Node to be deleted. Assume that it has just one child
* @param child Assume it is a child of the parent
*/
private fun removeSingleChildNode(parent: Node, child: Node) {
parent.key = child.key
parent.left = child.left
parent.right = child.right
}
fun visit(): Array<Int> {
val a = left?.visit() ?: emptyArray()
val b = right?.visit() ?: emptyArray()
return a + arrayOf(key) + b
}
}

View File

@ -0,0 +1,23 @@
package com.baeldung.interfaces
interface BaseInterface {
fun someMethod(): String
}
interface FirstChildInterface : BaseInterface {
override fun someMethod(): String {
return("Hello, from someMethod in FirstChildInterface")
}
}
interface SecondChildInterface : BaseInterface {
override fun someMethod(): String {
return("Hello, from someMethod in SecondChildInterface")
}
}
class ChildClass : FirstChildInterface, SecondChildInterface {
override fun someMethod(): String {
return super<SecondChildInterface>.someMethod()
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.interfaces
interface MyInterface {
fun someMethod(): String
}
class MyClass() : MyInterface {
override fun someMethod(): String {
return("Hello, World!")
}
}
class MyDerivedClass(myInterface: MyInterface) : MyInterface by myInterface

View File

@ -0,0 +1,29 @@
package com.baeldung.interfaces
interface FirstInterface {
fun someMethod(): String
fun anotherMethod(): String {
return("Hello, from anotherMethod in FirstInterface")
}
}
interface SecondInterface {
fun someMethod(): String {
return("Hello, from someMethod in SecondInterface")
}
fun anotherMethod(): String {
return("Hello, from anotherMethod in SecondInterface")
}
}
class SomeClass: FirstInterface, SecondInterface {
override fun someMethod(): String {
return("Hello, from someMethod in SomeClass")
}
override fun anotherMethod(): String {
return("Hello, from anotherMethod in SomeClass")
}
}

View File

@ -0,0 +1,24 @@
package com.baeldung.interfaces
interface SimpleInterface {
val firstProp: String
val secondProp: String
get() = "Second Property"
fun firstMethod(): String
fun secondMethod(): String {
println("Hello, from: " + secondProp)
return ""
}
}
class SimpleClass: SimpleInterface {
override val firstProp: String = "First Property"
override val secondProp: String
get() = "Second Property, Overridden!"
override fun firstMethod(): String {
return("Hello, from: " + firstProp)
}
override fun secondMethod(): String {
return("Hello, from: " + secondProp + firstProp)
}
}

View File

@ -0,0 +1,319 @@
package com.baeldung.datastructures
import org.junit.After
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
class NodeTest {
@Before
fun setUp() {
}
@After
fun tearDown() {
}
/**
* Test suit for finding the node by value
* Partition the tests as follows:
* 1. tree depth: 0, 1, > 1
* 2. pivot depth location: not present, 0, 1, 2, > 2
*/
/**
* Find the node by value
* 1. tree depth: 0
* 2. pivot depth location: not present
*/
@Test
fun givenDepthZero_whenPivotNotPresent_thenNull() {
val n = Node(1)
assertNull(n.find(2))
}
/**
* Find the node by value
* 1. tree depth: 0
* 2. pivot depth location: 0
*/
@Test
fun givenDepthZero_whenPivotDepthZero_thenReturnNodeItself() {
val n = Node(1)
assertEquals(n, n.find(1))
}
/**
* Find the node by value
* 1. tree depth: 1
* 2. pivot depth location: not present
*/
@Test
fun givenDepthOne_whenPivotNotPresent_thenNull() {
val n = Node(1, Node(0))
assertNull(n.find(2))
}
/**
* Find the node by value
* 1. tree depth: 1
* 2. pivot depth location: not present
*/
@Test
fun givenDepthOne_whenPivotAtDepthOne_thenSuccess() {
val n = Node(1, Node(0))
assertEquals(n.left, n.find(0)
)
}
@Test
fun givenDepthTwo_whenPivotAtDepth2_then_Success() {
val left = Node(1, Node(0), Node(2))
val right = Node(5, Node(4), Node(6))
val n = Node(3, left, right)
assertEquals(left.left, n.find(0))
}
/**
* Test suit for inserting a value
* Partition the test as follows:
* 1. tree depth: 0, 1, 2, > 2
* 2. depth to insert: 0, 1, > 1
* 3. is duplicate: no, yes
* 4. sub-tree: left, right
*/
/**
* Test for inserting a value
* 1. tree depth: 0
* 2. depth to insert: 1
* 3. is duplicate: no
* 4. sub-tree: right
*/
@Test
fun givenTreeDepthZero_whenInsertNoDuplicateToRight_thenAddNode() {
val n = Node(1)
n.insert(2)
assertEquals(1, n.key)
with(n.right!!) {
assertEquals(2, key)
assertNull(left)
assertNull(right)
}
assertNull(n.left)
}
/**
* Test for inserting a value
* 1. tree depth: 0
* 2. depth to insert: 1
* 3. is duplicate: no
* 4. sub-tree: right
*/
@Test
fun givenTreeDepthZero_whenInsertNoDuplicateToLeft_thenSuccess() {
val n = Node(1)
n.insert(0)
assertEquals(1, n.key)
with(n.left!!) {
assertEquals(0, key)
assertNull(left)
assertNull(right)
}
assertNull(n.right)
}
/**
* Test for inserting a value
* 1. tree depth: 0
* 2. depth to insert: 1
* 3. is duplicate: yes
*/
@Test
fun givenTreeDepthZero_whenInsertDuplicate_thenSuccess() {
val n = Node(1)
n.insert(1)
assertEquals(1, n.key)
assertNull(n.right)
assertNull(n.left)
}
/**
* Test suit for inserting a value
* Partition the test as follows:
* 1. tree depth: 0, 1, 2, > 2
* 2. depth to insert: 0, 1, > 1
* 3. is duplicate: no, yes
* 4. sub-tree: left, right
*/
/**
* Test for inserting a value
* 1. tree depth: 1
* 2. depth to insert: 1
* 3. is duplicate: no
* 4. sub-tree: right
*/
@Test
fun givenTreeDepthOne_whenInsertNoDuplicateToRight_thenSuccess() {
val n = Node(10, Node(3))
n.insert(15)
assertEquals(10, n.key)
with(n.right!!) {
assertEquals(15, key)
assertNull(left)
assertNull(right)
}
with(n.left!!) {
assertEquals(3, key)
assertNull(left)
assertNull(right)
}
}
/**
* Test for inserting a value
* 1. tree depth: 1
* 2. depth to insert: 1
* 3. is duplicate: no
* 4. sub-tree: left
*/
@Test
fun givenTreeDepthOne_whenInsertNoDuplicateToLeft_thenAddNode() {
val n = Node(10, null, Node(15))
n.insert(3)
assertEquals(10, n.key)
with(n.right!!) {
assertEquals(15, key)
assertNull(left)
assertNull(right)
}
with(n.left!!) {
assertEquals(3, key)
assertNull(left)
assertNull(right)
}
}
/**
* Test for inserting a value
* 1. tree depth: 1
* 2. depth to insert: 1
* 3. is duplicate: yes
*/
@Test
fun givenTreeDepthOne_whenInsertDuplicate_thenNoChange() {
val n = Node(10, null, Node(15))
n.insert(15)
assertEquals(10, n.key)
with(n.right!!) {
assertEquals(15, key)
assertNull(left)
assertNull(right)
}
assertNull(n.left)
}
/**
* Test suit for removal
* Partition the input as follows:
* 1. tree depth: 0, 1, 2, > 2
* 2. value to delete: absent, present
* 3. # child nodes: 0, 1, 2
*/
/**
* Test for removal value
* 1. tree depth: 0
* 2. value to delete: absent
*/
@Test
fun givenTreeDepthZero_whenValueAbsent_thenNoChange() {
val n = Node(1)
n.delete(0)
assertEquals(1, n.key)
assertNull(n.left)
assertNull(n.right)
}
/**
* Test for removal
* 1. tree depth: 1
* 2. value to delete: absent
*/
@Test
fun givenTreeDepthOne_whenValueAbsent_thenNoChange() {
val n = Node(1, Node(0), Node(2))
n.delete(3)
assertEquals(1, n.key)
assertEquals(2, n.right!!.key)
with(n.left!!) {
assertEquals(0, key)
assertNull(left)
assertNull(right)
}
with(n.right!!) {
assertNull(left)
assertNull(right)
}
}
/**
* Test suit for removal
* 1. tree depth: 1
* 2. value to delete: present
* 3. # child nodes: 0
*/
@Test
fun givenTreeDepthOne_whenNodeToDeleteHasNoChildren_thenChangeTree() {
val n = Node(1, Node(0))
n.delete(0)
assertEquals(1, n.key)
assertNull(n.left)
assertNull(n.right)
}
/**
* Test suit for removal
* 1. tree depth: 2
* 2. value to delete: present
* 3. # child nodes: 1
*/
@Test
fun givenTreeDepthTwo_whenNodeToDeleteHasOneChild_thenChangeTree() {
val n = Node(2, Node(0, null, Node(1)), Node(3))
n.delete(0)
assertEquals(2, n.key)
with(n.right!!) {
assertEquals(3, key)
assertNull(left)
assertNull(right)
}
with(n.left!!) {
assertEquals(1, key)
assertNull(left)
assertNull(right)
}
}
@Test
fun givenTreeDepthThree_whenNodeToDeleteHasTwoChildren_thenChangeTree() {
val l = Node(2, Node(1), Node(5, Node(4), Node(6)))
val r = Node(10, Node(9), Node(11))
val n = Node(8, l, r)
n.delete(8)
assertEquals(6, n.key)
with(n.left!!) {
assertEquals(2, key)
assertEquals(1, left!!.key)
assertEquals(5, right!!.key)
assertEquals(4, right!!.left!!.key)
}
with(n.right!!) {
assertEquals(10, key)
assertEquals(9, left!!.key)
assertEquals(11, right!!.key)
}
}
}

View File

@ -0,0 +1,32 @@
package com.baeldung.interfaces
import org.junit.Test
import kotlin.test.assertEquals
class InterfaceExamplesUnitTest {
@Test
fun givenAnInterface_whenImplemented_thenBehavesAsOverridden() {
val simpleClass = SimpleClass()
assertEquals("Hello, from: First Property", simpleClass.firstMethod())
assertEquals("Hello, from: Second Property, Overridden!First Property", simpleClass.secondMethod())
}
@Test
fun givenMultipleInterfaces_whenImplemented_thenBehavesAsOverridden() {
val someClass = SomeClass()
assertEquals("Hello, from someMethod in SomeClass", someClass.someMethod())
assertEquals("Hello, from anotherMethod in SomeClass", someClass.anotherMethod())
}
@Test
fun givenConflictingInterfaces_whenImplemented_thenBehavesAsOverridden() {
val childClass = ChildClass()
assertEquals("Hello, from someMethod in SecondChildInterface", childClass.someMethod())
}
@Test
fun givenAnInterface_whenImplemented_thenBehavesAsDelegated() {
val myClass = MyClass()
assertEquals("Hello, World!", MyDerivedClass(myClass).someMethod())
}
}

View File

@ -0,0 +1,121 @@
package com.baeldung.kotlin
import org.junit.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
class StructuralJumpUnitTest {
@Test
fun givenLoop_whenBreak_thenComplete() {
var value = ""
for (i in "hello_world") {
if (i == '_')
break
value += i.toString()
}
assertEquals("hello", value)
}
@Test
fun givenLoop_whenBreakWithLabel_thenComplete() {
var value = ""
outer_loop@ for (i in 'a'..'d') {
for (j in 1..3) {
value += "" + i + j
if (i == 'b' && j == 1)
break@outer_loop
}
}
assertEquals("a1a2a3b1", value)
}
@Test
fun givenLoop_whenContinue_thenComplete() {
var result = ""
for (i in "hello_world") {
if (i == '_')
continue
result += i
}
assertEquals("helloworld", result)
}
@Test
fun givenLoop_whenContinueWithLabel_thenComplete() {
var result = ""
outer_loop@ for (i in 'a'..'c') {
for (j in 1..3) {
if (i == 'b')
continue@outer_loop
result += "" + i + j
}
}
assertEquals("a1a2a3c1c2c3", result)
}
@Test
fun givenLambda_whenReturn_thenComplete() {
var result = returnInLambda();
assertEquals("hello", result)
}
private fun returnInLambda(): String {
var result = ""
"hello_world".forEach {
// non-local return directly to the caller
if (it == '_') return result
result += it.toString()
}
//this line won't be reached
return result;
}
@Test
fun givenLambda_whenReturnWithExplicitLabel_thenComplete() {
var result = ""
"hello_world".forEach lit@{
if (it == '_') {
// local return to the caller of the lambda, i.e. the forEach loop
return@lit
}
result += it.toString()
}
assertEquals("helloworld", result)
}
@Test
fun givenLambda_whenReturnWithImplicitLabel_thenComplete() {
var result = ""
"hello_world".forEach {
if (it == '_') {
// local return to the caller of the lambda, i.e. the forEach loop
return@forEach
}
result += it.toString()
}
assertEquals("helloworld", result)
}
@Test
fun givenAnonymousFunction_return_thenComplete() {
var result = ""
"hello_world".forEach(fun(element) {
// local return to the caller of the anonymous fun, i.e. the forEach loop
if (element == '_') return
result += element.toString()
})
assertEquals("helloworld", result)
}
@Test
fun givenAnonymousFunction_returnToLabel_thenComplete() {
var result = ""
run loop@{
"hello_world".forEach {
// non-local return from the lambda passed to run
if (it == '_') return@loop
result += it.toString()
}
}
assertEquals("hello", result)
}
}

View File

@ -0,0 +1,3 @@
### Relevant articles
- [CDI Portable Extension and Flyway](https://www.baeldung.com/cdi-portable-extension)

View File

@ -0,0 +1,25 @@
plugins {
// Apply the java-library plugin to add support for Java Library
id 'java-library'
}
dependencies {
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.3.1'
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.3.1'
// Only necessary for JUnit 3 and 4 tests
testCompileOnly 'junit:junit:4.12'
testRuntimeOnly 'org.junit.vintage:junit-vintage-engine:5.3.1'
}
repositories {
jcenter()
}
test {
useJUnitPlatform {
includeTags 'fast'
excludeTags 'slow'
}
}

View File

@ -0,0 +1,12 @@
package com.example;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class CalculatorJUnit4Test {
@Test
public void testAdd() {
assertEquals(42, Integer.sum(19, 23));
}
}

View File

@ -0,0 +1,36 @@
package com.example;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;;
public class CalculatorJUnit5Test {
@Tag("fast")
@Test
public void testAdd() {
assertEquals(42, Integer.sum(19, 23));
}
@Tag("slow")
@Test
public void testAddMaxInteger() {
assertEquals(2147483646, Integer.sum(2147183646, 300000));
}
@Tag("fast")
@Test
public void testAddZero() {
assertEquals(21, Integer.sum(21, 0));
}
@Tag("fast")
@Test
public void testDivide() {
assertThrows(ArithmeticException.class, () -> {
Integer.divideUnsigned(42, 0);
});
}
}

View File

@ -5,6 +5,6 @@ include 'greeting-library'
include 'greeting-library-java'
include 'greeter'
include 'gradletaskdemo'
include 'junit5'
println 'This will be executed during the initialization phase.'

View File

@ -0,0 +1,23 @@
=========
## Guava and Hamcrest Cookbooks and Examples
### Relevant Articles:
- [Guava Collections Cookbook](http://www.baeldung.com/guava-collections)
- [Guava Ordering Cookbook](http://www.baeldung.com/guava-order)
- [Hamcrest Collections Cookbook](http://www.baeldung.com/hamcrest-collections-arrays)
- [Partition a List in Java](http://www.baeldung.com/java-list-split)
- [Filtering and Transforming Collections in Guava](http://www.baeldung.com/guava-filter-and-transform-a-collection)
- [Guava Join and Split Collections](http://www.baeldung.com/guava-joiner-and-splitter-tutorial)
- [Guava Lists](http://www.baeldung.com/guava-lists)
- [Guava Sets](http://www.baeldung.com/guava-sets)
- [Guava Maps](http://www.baeldung.com/guava-maps)
- [Guide to Guava Multimap](http://www.baeldung.com/guava-multimap)
- [Guide to Guava RangeSet](http://www.baeldung.com/guava-rangeset)
- [Guide to Guava RangeMap](http://www.baeldung.com/guava-rangemap)
- [Guide to Guava MinMaxPriorityQueue and EvictingQueue](http://www.baeldung.com/guava-minmax-priority-queue-and-evicting-queue)
- [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap)
- [Guava Set + Function = Map](http://www.baeldung.com/guava-set-function-map-tutorial)
- [Guide to Guava Table](http://www.baeldung.com/guava-table)
- [Guide to Guava ClassToInstanceMap](http://www.baeldung.com/guava-class-to-instance-map)

66
guava-collections/pom.xml Normal file
View File

@ -0,0 +1,66 @@
<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>guava-collections</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>guava-collections</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-java</relativePath>
</parent>
<dependencies>
<!-- utils -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>${commons-collections4.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<!-- test scoped -->
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hamcrest/java-hamcrest -->
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>java-hamcrest</artifactId>
<version>${java-hamcrest.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>guava</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
<properties>
<!-- util -->
<guava.version>24.0-jre</guava.version>
<commons-lang3.version>3.5</commons-lang3.version>
<commons-collections4.version>4.1</commons-collections4.version>
<!-- testing -->
<assertj.version>3.6.1</assertj.version>
<java-hamcrest.version>2.0.0.0</java-hamcrest.version>
</properties>
</project>

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