Merge branch 'eugenp:master' into master
This commit is contained in:
@@ -65,6 +65,9 @@ core-java-io/target_link.txt
|
||||
core-java/src/main/java/com/baeldung/manifest/MANIFEST.MF
|
||||
ethereum/logs/
|
||||
jmeter/src/main/resources/*-JMeter.csv
|
||||
jmeter/src/main/resources/*-Basic*.csv
|
||||
jmeter/src/main/resources/*-JMeter*.csv
|
||||
|
||||
ninja/devDb.mv.db
|
||||
|
||||
**/node_modules/
|
||||
|
||||
@@ -4,4 +4,5 @@
|
||||
- [Sorting Strings by Contained Numbers in Java](https://www.baeldung.com/java-sort-strings-contained-numbers)
|
||||
- [Guide to In-Place Sorting Algorithm Works with a Java Implementation](https://www.baeldung.com/java-in-place-sorting)
|
||||
- [Partitioning and Sorting Arrays with Many Repeated Entries with Java Examples](https://www.baeldung.com/java-sorting-arrays-with-repeated-entries)
|
||||
- [Gravity/Bead Sort in Java](https://www.baeldung.com/java-gravity-bead-sort)
|
||||
- More articles: [[<-- prev]](/algorithms-sorting)
|
||||
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
package com.baeldung.algorithms.gravitysort;
|
||||
|
||||
public class GravitySort {
|
||||
|
||||
public static int findMax(int[] A) {
|
||||
int max = A[0];
|
||||
for (int i = 1; i< A.length; i++) {
|
||||
if (A[i] > max) {
|
||||
max = A[i];
|
||||
}
|
||||
}
|
||||
return max;
|
||||
}
|
||||
|
||||
public static boolean[][] setupAbacus(int[] A, int m) {
|
||||
boolean[][] abacus = new boolean[A.length][m];
|
||||
for (int i = 0; i < abacus.length; i++) {
|
||||
int number = A[i];
|
||||
for (int j = 0; j < abacus[0].length && j < number; j++) {
|
||||
abacus[A.length - 1 - i][j] = true;
|
||||
}
|
||||
}
|
||||
return abacus;
|
||||
}
|
||||
|
||||
public static void dropBeads(boolean[][] abacus, int[] A, int m) {
|
||||
for (int i = 1; i < A.length; i++) {
|
||||
for (int j = m - 1; j >= 0; j--) {
|
||||
if (abacus[i][j] == true) {
|
||||
int x = i;
|
||||
while (x > 0 && abacus[x - 1][j] == false) {
|
||||
boolean temp = abacus[x - 1][j];
|
||||
abacus[x - 1][j] = abacus[x][j];
|
||||
abacus[x][j] = temp;
|
||||
x--;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void transformToList(boolean[][] abacus, int[] A) {
|
||||
int index = 0;
|
||||
for (int i = abacus.length - 1; i >= 0; i--) {
|
||||
int beads = 0;
|
||||
for (int j = 0; j < abacus[0].length && abacus[i][j] == true; j++) {
|
||||
beads++;
|
||||
}
|
||||
A[index++] = beads;
|
||||
}
|
||||
}
|
||||
|
||||
public static void sort(int[] A) {
|
||||
int m = findMax(A);
|
||||
boolean[][] abacus = setupAbacus(A, m);
|
||||
dropBeads(abacus, A, m);
|
||||
// transform abacus into sorted list
|
||||
transformToList(abacus, A);
|
||||
}
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package com.baeldung.algorithms.gravitysort;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class GravitySortUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenIntegerArray_whenSortedWithGravitySort_thenGetSortedArray() {
|
||||
int[] actual = { 9, 9, 100, 3, 57, 12, 3, 78, 0, 2, 2, 40, 21, 9 };
|
||||
int[] expected = { 0, 2, 2, 3, 3, 9, 9, 9, 12, 21, 40, 57, 78, 100 };
|
||||
GravitySort.sort(actual);
|
||||
Assert.assertArrayEquals(expected, actual);
|
||||
}
|
||||
}
|
||||
@@ -95,8 +95,8 @@
|
||||
|
||||
<properties>
|
||||
<json-simple.version>1.1.1</json-simple.version>
|
||||
<aws-lambda-java-events.version>1.3.0</aws-lambda-java-events.version>
|
||||
<aws-lambda-java-core.version>1.2.0</aws-lambda-java-core.version>
|
||||
<aws-lambda-java-events.version>3.11.0</aws-lambda-java-events.version>
|
||||
<aws-lambda-java-core.version>1.2.1</aws-lambda-java-core.version>
|
||||
<gson.version>2.8.2</gson.version>
|
||||
</properties>
|
||||
|
||||
|
||||
+21
-19
@@ -1,12 +1,12 @@
|
||||
package com.baeldung.lambda.dynamodb;
|
||||
|
||||
import com.amazonaws.regions.Region;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import com.amazonaws.regions.Regions;
|
||||
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient;
|
||||
import com.amazonaws.services.dynamodbv2.document.DynamoDB;
|
||||
import com.amazonaws.services.dynamodbv2.document.Item;
|
||||
import com.amazonaws.services.dynamodbv2.document.PutItemOutcome;
|
||||
import com.amazonaws.services.dynamodbv2.document.spec.PutItemSpec;
|
||||
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
|
||||
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder;
|
||||
import com.amazonaws.services.dynamodbv2.model.AttributeValue;
|
||||
import com.amazonaws.services.dynamodbv2.model.ConditionalCheckFailedException;
|
||||
import com.amazonaws.services.lambda.runtime.Context;
|
||||
import com.amazonaws.services.lambda.runtime.RequestHandler;
|
||||
@@ -15,7 +15,7 @@ import com.baeldung.lambda.dynamodb.bean.PersonResponse;
|
||||
|
||||
public class SavePersonHandler implements RequestHandler<PersonRequest, PersonResponse> {
|
||||
|
||||
private DynamoDB dynamoDb;
|
||||
private AmazonDynamoDB amazonDynamoDB;
|
||||
|
||||
private String DYNAMODB_TABLE_NAME = "Person";
|
||||
private Regions REGION = Regions.US_WEST_2;
|
||||
@@ -30,20 +30,22 @@ public class SavePersonHandler implements RequestHandler<PersonRequest, PersonRe
|
||||
return personResponse;
|
||||
}
|
||||
|
||||
private PutItemOutcome persistData(PersonRequest personRequest) throws ConditionalCheckFailedException {
|
||||
return this.dynamoDb.getTable(DYNAMODB_TABLE_NAME)
|
||||
.putItem(
|
||||
new PutItemSpec().withItem(new Item()
|
||||
.withNumber("id", personRequest.getId())
|
||||
.withString("firstName", personRequest.getFirstName())
|
||||
.withString("lastName", personRequest.getLastName())
|
||||
.withNumber("age", personRequest.getAge())
|
||||
.withString("address", personRequest.getAddress())));
|
||||
private void persistData(PersonRequest personRequest) throws ConditionalCheckFailedException {
|
||||
|
||||
Map<String, AttributeValue> attributesMap = new HashMap<>();
|
||||
|
||||
attributesMap.put("id", new AttributeValue(String.valueOf(personRequest.getId())));
|
||||
attributesMap.put("firstName", new AttributeValue(personRequest.getFirstName()));
|
||||
attributesMap.put("lastName", new AttributeValue(personRequest.getLastName()));
|
||||
attributesMap.put("age", new AttributeValue(String.valueOf(personRequest.getAge())));
|
||||
attributesMap.put("address", new AttributeValue(personRequest.getAddress()));
|
||||
|
||||
amazonDynamoDB.putItem(DYNAMODB_TABLE_NAME, attributesMap);
|
||||
}
|
||||
|
||||
private void initDynamoDbClient() {
|
||||
AmazonDynamoDBClient client = new AmazonDynamoDBClient();
|
||||
client.setRegion(Region.getRegion(REGION));
|
||||
this.dynamoDb = new DynamoDB(client);
|
||||
this.amazonDynamoDB = AmazonDynamoDBClientBuilder.standard()
|
||||
.withRegion(REGION)
|
||||
.build();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -91,7 +91,7 @@
|
||||
|
||||
<properties>
|
||||
<spring.version>2.2.1.RELEASE</spring.version>
|
||||
<awssdk.version>2.10.27</awssdk.version>
|
||||
<awssdk.version>2.17.283</awssdk.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
+32
-80
@@ -3,17 +3,11 @@
|
||||
*/
|
||||
package com.baeldung.aws.reactive.s3;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.Map;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
import org.springframework.core.io.buffer.DataBuffer;
|
||||
import org.springframework.core.io.buffer.DataBufferUtils;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.http.ResponseEntity.BodyBuilder;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
@@ -22,11 +16,7 @@ import org.springframework.web.bind.annotation.RestController;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
import software.amazon.awssdk.core.ResponseBytes;
|
||||
import software.amazon.awssdk.core.SdkResponse;
|
||||
import software.amazon.awssdk.core.async.AsyncResponseTransformer;
|
||||
import software.amazon.awssdk.core.async.SdkPublisher;
|
||||
import software.amazon.awssdk.core.internal.async.ByteArrayAsyncResponseTransformer;
|
||||
import software.amazon.awssdk.http.SdkHttpResponse;
|
||||
import software.amazon.awssdk.services.s3.S3AsyncClient;
|
||||
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
|
||||
@@ -40,38 +30,39 @@ import software.amazon.awssdk.services.s3.model.GetObjectResponse;
|
||||
@RequestMapping("/inbox")
|
||||
@Slf4j
|
||||
public class DownloadResource {
|
||||
|
||||
|
||||
|
||||
private final S3AsyncClient s3client;
|
||||
private final S3ClientConfigurarionProperties s3config;
|
||||
|
||||
public DownloadResource(S3AsyncClient s3client, S3ClientConfigurarionProperties s3config) {
|
||||
this.s3client = s3client;
|
||||
this.s3config = s3config;
|
||||
this.s3config = s3config;
|
||||
}
|
||||
|
||||
|
||||
@GetMapping(path="/{filekey}")
|
||||
public Mono<ResponseEntity<Flux<ByteBuffer>>> downloadFile(@PathVariable("filekey") String filekey) {
|
||||
|
||||
GetObjectRequest request = GetObjectRequest.builder()
|
||||
.bucket(s3config.getBucket())
|
||||
.key(filekey)
|
||||
.build();
|
||||
|
||||
return Mono.fromFuture(s3client.getObject(request,new FluxResponseProvider()))
|
||||
.map( (response) -> {
|
||||
checkResult(response.sdkResponse);
|
||||
String filename = getMetadataItem(response.sdkResponse,"filename",filekey);
|
||||
|
||||
log.info("[I65] filename={}, length={}",filename, response.sdkResponse.contentLength() );
|
||||
|
||||
return ResponseEntity.ok()
|
||||
.header(HttpHeaders.CONTENT_TYPE, response.sdkResponse.contentType())
|
||||
.header(HttpHeaders.CONTENT_LENGTH, Long.toString(response.sdkResponse.contentLength()))
|
||||
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + filename + "\"")
|
||||
.body(response.flux);
|
||||
});
|
||||
@GetMapping(path = "/{filekey}")
|
||||
public Mono<ResponseEntity<Flux<ByteBuffer>>> downloadFile(@PathVariable("filekey") String filekey) {
|
||||
|
||||
GetObjectRequest request = GetObjectRequest.builder()
|
||||
.bucket(s3config.getBucket())
|
||||
.key(filekey)
|
||||
.build();
|
||||
|
||||
return Mono.fromFuture(s3client.getObject(request, AsyncResponseTransformer.toPublisher()))
|
||||
.map(response -> {
|
||||
checkResult(response.response());
|
||||
String filename = getMetadataItem(response.response(), "filename", filekey);
|
||||
|
||||
log.info("[I65] filename={}, length={}", filename, response.response()
|
||||
.contentLength());
|
||||
|
||||
return ResponseEntity.ok()
|
||||
.header(HttpHeaders.CONTENT_TYPE, response.response()
|
||||
.contentType())
|
||||
.header(HttpHeaders.CONTENT_LENGTH, Long.toString(response.response()
|
||||
.contentLength()))
|
||||
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + filename + "\"")
|
||||
.body(Flux.from(response));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -82,63 +73,24 @@ public class DownloadResource {
|
||||
* @return
|
||||
*/
|
||||
private String getMetadataItem(GetObjectResponse sdkResponse, String key, String defaultValue) {
|
||||
for( Entry<String, String> entry : sdkResponse.metadata().entrySet()) {
|
||||
if ( entry.getKey().equalsIgnoreCase(key)) {
|
||||
for (Entry<String, String> entry : sdkResponse.metadata()
|
||||
.entrySet()) {
|
||||
if (entry.getKey()
|
||||
.equalsIgnoreCase(key)) {
|
||||
return entry.getValue();
|
||||
}
|
||||
}
|
||||
return defaultValue;
|
||||
}
|
||||
|
||||
|
||||
// Helper used to check return codes from an API call
|
||||
private static void checkResult(GetObjectResponse response) {
|
||||
SdkHttpResponse sdkResponse = response.sdkHttpResponse();
|
||||
if ( sdkResponse != null && sdkResponse.isSuccessful()) {
|
||||
if (sdkResponse != null && sdkResponse.isSuccessful()) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
throw new DownloadFailedException(response);
|
||||
}
|
||||
|
||||
|
||||
static class FluxResponseProvider implements AsyncResponseTransformer<GetObjectResponse,FluxResponse> {
|
||||
|
||||
private FluxResponse response;
|
||||
|
||||
@Override
|
||||
public CompletableFuture<FluxResponse> prepare() {
|
||||
response = new FluxResponse();
|
||||
return response.cf;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onResponse(GetObjectResponse sdkResponse) {
|
||||
this.response.sdkResponse = sdkResponse;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onStream(SdkPublisher<ByteBuffer> publisher) {
|
||||
response.flux = Flux.from(publisher);
|
||||
response.cf.complete(response);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void exceptionOccurred(Throwable error) {
|
||||
response.cf.completeExceptionally(error);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Holds the API response and stream
|
||||
* @author Philippe
|
||||
*/
|
||||
static class FluxResponse {
|
||||
|
||||
final CompletableFuture<FluxResponse> cf = new CompletableFuture<>();
|
||||
GetObjectResponse sdkResponse;
|
||||
Flux<ByteBuffer> flux;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+1
-1
@@ -22,7 +22,7 @@
|
||||
</modules>
|
||||
|
||||
<properties>
|
||||
<aws-java-sdk.version>1.11.290</aws-java-sdk.version>
|
||||
<aws-java-sdk.version>1.12.331</aws-java-sdk.version>
|
||||
<maven-shade-plugin.version>3.0.0</maven-shade-plugin.version>
|
||||
</properties>
|
||||
|
||||
|
||||
+1
-1
@@ -13,4 +13,4 @@ One script is included to easily start middleware using Docker:
|
||||
- [A Guide to the Axon Framework](https://www.baeldung.com/axon-cqrs-event-sourcing)
|
||||
- [Multi-Entity Aggregates in Axon](https://www.baeldung.com/java-axon-multi-entity-aggregates)
|
||||
- [Snapshotting Aggregates in Axon](https://www.baeldung.com/axon-snapshotting-aggregates)
|
||||
- [Dispatching Queries in Axon Framework](https://www.baeldung.com/axon-query-dispatching/)
|
||||
- [Dispatching Queries in Axon Framework](https://www.baeldung.com/axon-query-dispatching)
|
||||
|
||||
@@ -3,7 +3,10 @@
|
||||
xsi:schemaLocation="http://pmd.sf.net/ruleset/1.0.0 http://pmd.sf.net/ruleset_xml_schema.xsd"
|
||||
xsi:noNamespaceSchemaLocation="http://pmd.sf.net/ruleset_xml_schema.xsd">
|
||||
<description>Baeldung custom PMD rules</description>
|
||||
<rule name="UnitTestMustFollowNamingConventionRule" message="Unit test class names need to end in 'UnitTest', integration tests with 'IntegrationTest', etc " class="org.baeldung.pmd.UnitTestNamingConventionRule">
|
||||
<rule name="UnitTestMustFollowNamingConventionRule"
|
||||
message="Unit test class names need to end in 'UnitTest', integration tests with 'IntegrationTest', etc "
|
||||
class="org.baeldung.pmd.UnitTestNamingConventionRule"
|
||||
language="java">
|
||||
<description>Test does not follow Baeldung naming convention</description>
|
||||
<priority>3</priority>
|
||||
</rule>
|
||||
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
package com.baeldung.arrayslicing;
|
||||
|
||||
import org.apache.commons.lang3.ArrayUtils;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
|
||||
public class SlicingArrayUnitTest {
|
||||
private static final String[] LANGUAGES = new String[] { "Python", "Java", "Kotlin", "Scala", "Ruby", "Go", "Rust" };
|
||||
private static final String[] JVM_LANGUAGES = new String[] { "Java", "Kotlin", "Scala" };
|
||||
|
||||
@Test
|
||||
void givenAnArray_whenSlicingUsingStream_shouldGetExpectedResult() {
|
||||
String[] result = Arrays.stream(LANGUAGES, 1, 4).toArray(String[]::new);
|
||||
assertArrayEquals(JVM_LANGUAGES, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenAnArray_whenSlicingUsingArraysCopyOfRange_shouldGetExpectedResult() {
|
||||
String[] result = Arrays.copyOfRange(LANGUAGES, 1, 4);
|
||||
assertArrayEquals(JVM_LANGUAGES, result);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
void givenAnArray_whenSlicingUsingSystemArraycopy_shouldGetExpectedResult() {
|
||||
String[] result = new String[3];
|
||||
System.arraycopy(LANGUAGES, 1, result, 0, 3);
|
||||
assertArrayEquals(JVM_LANGUAGES, result);
|
||||
|
||||
String[] result2 = new String[] { "value one", "value two", "value three", "value four", "value five", "value six", "value seven" };
|
||||
System.arraycopy(LANGUAGES, 1, result2, 2, 3);
|
||||
assertArrayEquals(new String[] { "value one", "value two", "Java", "Kotlin", "Scala", "value six", "value seven" }, result2);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenAnArray_whenSlicingUsingArrayUtils_shouldGetExpectedResult() {
|
||||
String[] result = ArrayUtils.subarray(LANGUAGES, 1, 4);
|
||||
assertArrayEquals(JVM_LANGUAGES, result);
|
||||
}
|
||||
}
|
||||
@@ -10,3 +10,4 @@ This module contains articles about Java array fundamentals. They assume no prev
|
||||
- [Removing an Element from an Array in Java](https://www.baeldung.com/java-array-remove-element)
|
||||
- [Removing the First Element of an Array](https://www.baeldung.com/java-array-remove-first-element)
|
||||
- [Extending an Array’s Length](https://www.baeldung.com/java-array-add-element-at-the-end)
|
||||
- [Initializing a Boolean Array in Java](https://www.baeldung.com/java-initializing-boolean-array)
|
||||
|
||||
@@ -10,3 +10,4 @@
|
||||
- [Create an Empty Map in Java](https://www.baeldung.com/java-create-empty-map)
|
||||
- [Sorting Objects in a List by Date](https://www.baeldung.com/java-sort-list-by-date)
|
||||
- [Fixed Size Queue Implementations in Java](https://www.baeldung.com/java-fixed-size-queue)
|
||||
- [Difference Between Java Enumeration and Iterator](https://www.baeldung.com/java-enumeration-vs-iterator)
|
||||
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package com.baeldung.enumerationiteratordifferences;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
public final class DataUtil {
|
||||
|
||||
private DataUtil() {
|
||||
}
|
||||
|
||||
static List<Person> getPersons() {
|
||||
Person person1 = new Person("amit", "kumar");
|
||||
Person person2 = new Person("yogi", "kuki");
|
||||
Person person3 = new Person("raj", "dosi");
|
||||
Person person4 = new Person("prakash", "kumar");
|
||||
return Arrays.asList(person1, person2, person3, person4);
|
||||
}
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package com.baeldung.enumerationiteratordifferences;
|
||||
|
||||
import java.util.Enumeration;
|
||||
import java.util.Vector;
|
||||
|
||||
import static com.baeldung.enumerationiteratordifferences.DataUtil.getPersons;
|
||||
|
||||
public class EnumerationExample {
|
||||
public static void main(String[] args) {
|
||||
|
||||
Vector<Person> people = new Vector<>(getPersons());
|
||||
Enumeration<Person> enumeration = people.elements();
|
||||
while (enumeration.hasMoreElements()) {
|
||||
System.out.println("First Name = " + enumeration.nextElement()
|
||||
.getFirstName());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package com.baeldung.enumerationiteratordifferences;
|
||||
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
|
||||
import static com.baeldung.enumerationiteratordifferences.DataUtil.getPersons;
|
||||
|
||||
public class IteratorExample {
|
||||
public static void main(String[] args) {
|
||||
List<Person> persons = getPersons();
|
||||
Iterator<Person> iterator = persons.iterator();
|
||||
while (iterator.hasNext()) {
|
||||
System.out.println("First Name = " + iterator.next()
|
||||
.getFirstName());
|
||||
}
|
||||
}
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
package com.baeldung.enumerationiteratordifferences;
|
||||
|
||||
public class Person {
|
||||
private String firstName;
|
||||
private String lastName;
|
||||
|
||||
public Person(String firstName, String lastName) {
|
||||
this.firstName = firstName;
|
||||
this.lastName = lastName;
|
||||
}
|
||||
|
||||
public String getFirstName() {
|
||||
return firstName;
|
||||
}
|
||||
|
||||
public void setFirstName(String firstName) {
|
||||
this.firstName = firstName;
|
||||
}
|
||||
|
||||
public String getLastName() {
|
||||
return lastName;
|
||||
}
|
||||
|
||||
public void setLastName(String lastName) {
|
||||
this.lastName = lastName;
|
||||
}
|
||||
}
|
||||
+2
-4
@@ -27,15 +27,13 @@ class ListToStringUnitTest {
|
||||
List<String> arraysAsList = Arrays.asList("ONE", "TWO", "THREE");
|
||||
|
||||
StringJoiner stringJoiner = new StringJoiner(",");
|
||||
arraysAsList.stream()
|
||||
.forEach(v -> stringJoiner.add(v));
|
||||
arraysAsList.forEach(stringJoiner::add);
|
||||
String commaSeparatedString = stringJoiner.toString();
|
||||
|
||||
assertThat(commaSeparatedString).isEqualTo("ONE,TWO,THREE");
|
||||
|
||||
StringJoiner stringJoinerWithDelimiterPrefixSuffix = new StringJoiner(",", "[", "]");
|
||||
arraysAsList.stream()
|
||||
.forEach(v -> stringJoinerWithDelimiterPrefixSuffix.add(v));
|
||||
arraysAsList.forEach(stringJoinerWithDelimiterPrefixSuffix::add);
|
||||
String commaSeparatedStringWithDelimiterPrefixSuffix = stringJoinerWithDelimiterPrefixSuffix.toString();
|
||||
|
||||
assertThat(commaSeparatedStringWithDelimiterPrefixSuffix).isEqualTo("[ONE,TWO,THREE]");
|
||||
|
||||
@@ -54,11 +54,11 @@
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<streamex.version>0.6.5</streamex.version>
|
||||
<streamex.version>0.8.1</streamex.version>
|
||||
<avaitility.version>1.7.0</avaitility.version>
|
||||
<eclipse-collections.version>8.2.0</eclipse-collections.version>
|
||||
<hppc.version>0.7.2</hppc.version>
|
||||
<fastutil.version>8.1.0</fastutil.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
</project>
|
||||
|
||||
@@ -15,6 +15,11 @@
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>jakarta.ws.rs</groupId>
|
||||
<artifactId>jakarta.ws.rs-api</artifactId>
|
||||
<version>3.1.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-collections4</artifactId>
|
||||
@@ -62,8 +67,8 @@
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<maven.compiler.source>1.9</maven.compiler.source>
|
||||
<maven.compiler.target>1.9</maven.compiler.target>
|
||||
<maven.compiler.source>11</maven.compiler.source>
|
||||
<maven.compiler.target>11</maven.compiler.target>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
package com.baeldung.multivaluedmap;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
|
||||
// Unit test for MultivaluedMap.
|
||||
public class MultivaluedMapUnitTest {
|
||||
|
||||
// Testing MultivaluedHashMap.
|
||||
@Test
|
||||
public void givenMultivaluedHashMap_whenEquals_thenTrue() {
|
||||
jakarta.ws.rs.core.MultivaluedMap<String, Integer> mulmap = new jakarta.ws.rs.core.MultivaluedHashMap<>();
|
||||
|
||||
// Mapping keys to values.
|
||||
mulmap.addAll("first", 1, 2, 3);
|
||||
mulmap.add(null, null);
|
||||
|
||||
assertNotNull(mulmap, "The MultivaluedHashMap is null!");
|
||||
assertEquals(1, mulmap.getFirst("first"), "The key isn't mapped to the right values!");
|
||||
assertEquals(null, mulmap.getFirst(null), "MultivaluedHashMap didn't accept null!");
|
||||
}
|
||||
|
||||
// Testing HashMap.
|
||||
@Test
|
||||
public void givenHashMap_whenEquals_thenTrue() {
|
||||
Map<String, Integer> map = new HashMap<>();
|
||||
|
||||
// Putting key-value pairs into our map.
|
||||
map.put("first", 1);
|
||||
map.put(null, 2);
|
||||
map.put("third", null);
|
||||
|
||||
assertNotNull(map, "The HashMap is null!");
|
||||
assertEquals(1, map.get("first"), "The key isn't mapped to the right value!");
|
||||
assertEquals(2, map.get(null), "HashMap didn't accept null as key!");
|
||||
assertEquals(null, map.get("third"), "HashMap didn't accept null value!");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
## Relevant articles
|
||||
|
||||
- [Using Streams to Collect Into a TreeSet](https://www.baeldung.com/java-stream-collect-into-treeset)
|
||||
- [A Guide to LinkedHashSet in Java](https://www.baeldung.com/java-linkedhashset)
|
||||
@@ -0,0 +1,39 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>core-java-collections-set-2</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>core-java-collections-set-2</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>${maven.compiler.source}</source>
|
||||
<target>${maven.compiler.target}</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source>8</maven.compiler.source>
|
||||
<maven.compiler.target>8</maven.compiler.target>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
package com.baeldung.treeset.collectintotreeset;
|
||||
|
||||
public class Player implements Comparable<Player> {
|
||||
private String name;
|
||||
private int age;
|
||||
private int numberOfPlayed;
|
||||
private int numberOfWins;
|
||||
|
||||
public Player(String name, int age, int numberOfPlayed, int numberOfWins) {
|
||||
this.name = name;
|
||||
this.age = age;
|
||||
this.numberOfPlayed = numberOfPlayed;
|
||||
this.numberOfWins = numberOfWins;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public int getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
public int getNumberOfPlayed() {
|
||||
return numberOfPlayed;
|
||||
}
|
||||
|
||||
public int getNumberOfWins() {
|
||||
return numberOfWins;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int compareTo(Player o) {
|
||||
return Integer.compare(age, o.age);
|
||||
}
|
||||
}
|
||||
+141
@@ -0,0 +1,141 @@
|
||||
package com.baeldung.linkedhashset;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
|
||||
public class LinkedHashSetUnitTest{
|
||||
|
||||
|
||||
@Test
|
||||
void whenCreatingLinkedHashSet_shouldBeEmpty(){
|
||||
Set<String> linkedHashSet = new LinkedHashSet<>();
|
||||
assertTrue(linkedHashSet.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenCreatingLinkedHashSetWithInitialCapacity_shouldBeEmpty(){
|
||||
LinkedHashSet<String> linkedHashSet = new LinkedHashSet<>(20);
|
||||
assertTrue(linkedHashSet.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenCreatingLinkedHashSetWithExistingCollection_shouldContainAllElementOfCollection(){
|
||||
Collection<String> data = Arrays.asList("first", "second", "third", "fourth", "fifth");
|
||||
LinkedHashSet<String> linkedHashSet = new LinkedHashSet<>(data);
|
||||
|
||||
assertFalse(linkedHashSet.isEmpty());
|
||||
assertEquals(data.size(), linkedHashSet.size());
|
||||
assertTrue(linkedHashSet.containsAll(data) && data.containsAll(linkedHashSet));
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenCreatingLinkedHashSetWithInitialCapacityAndLoadFactor_shouldBeEmpty(){
|
||||
LinkedHashSet<String> linkedHashSet = new LinkedHashSet<>(20, 3);
|
||||
assertTrue(linkedHashSet.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenAddingElement_shouldAddElement(){
|
||||
Set<Integer> linkedHashSet = new LinkedHashSet<>();
|
||||
assertTrue(linkedHashSet.add(0));
|
||||
assertFalse(linkedHashSet.add(0));
|
||||
assertTrue(linkedHashSet.contains(0));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenAddingCollection_shouldAddAllContentOfCollection(){
|
||||
Collection<Integer> data = Arrays.asList(1,2,3);
|
||||
LinkedHashSet<Integer> linkedHashSet = new LinkedHashSet<>();
|
||||
|
||||
assertTrue(linkedHashSet.addAll(data));
|
||||
assertTrue(data.containsAll(linkedHashSet) && linkedHashSet.containsAll(data));
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenAddingCollectionWithDuplicateElements_shouldMaintainUniqueValuesInSet(){
|
||||
LinkedHashSet<Integer> linkedHashSet = new LinkedHashSet<>();
|
||||
linkedHashSet.add(2);
|
||||
Collection<Integer> data = Arrays.asList(1, 1, 2, 3);
|
||||
|
||||
assertTrue(linkedHashSet.addAll(data));
|
||||
assertEquals(3, linkedHashSet.size());
|
||||
assertTrue(data.containsAll(linkedHashSet) && linkedHashSet.containsAll(data));
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenIteratingWithIterator_assertThatElementIsPresent(){
|
||||
LinkedHashSet<Integer> linkedHashSet = new LinkedHashSet<>();
|
||||
linkedHashSet.add(0);
|
||||
linkedHashSet.add(1);
|
||||
linkedHashSet.add(2);
|
||||
|
||||
Iterator<Integer> iterator = linkedHashSet.iterator();
|
||||
for (int i = 0; i < linkedHashSet.size(); i++) {
|
||||
int nextData = iterator.next();
|
||||
assertEquals(i, nextData);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenIteratingWithSpliterator_assertThatElementIsPresent(){
|
||||
LinkedHashSet<Integer> linkedHashSet = new LinkedHashSet<>();
|
||||
linkedHashSet.add(0);
|
||||
linkedHashSet.add(1);
|
||||
linkedHashSet.add(2);
|
||||
|
||||
Spliterator<Integer> spliterator = linkedHashSet.spliterator();
|
||||
AtomicInteger counter = new AtomicInteger();
|
||||
spliterator.forEachRemaining(data -> {
|
||||
assertEquals(counter.get(), (int)data);
|
||||
counter.getAndIncrement();
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenRemovingAnElement_shouldRemoveElement(){
|
||||
Collection<String> data = Arrays.asList("first", "second", "third", "fourth", "fifth");
|
||||
LinkedHashSet<String> linkedHashSet = new LinkedHashSet<>(data);
|
||||
|
||||
assertTrue(linkedHashSet.remove("second"));
|
||||
assertFalse(linkedHashSet.contains("second"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenRemovingAnElementGreaterThanTwo_shouldRemoveElement(){
|
||||
LinkedHashSet<Integer> linkedHashSet = new LinkedHashSet<>();
|
||||
linkedHashSet.add(0);
|
||||
linkedHashSet.add(1);
|
||||
linkedHashSet.add(2);
|
||||
linkedHashSet.add(3);
|
||||
linkedHashSet.add(4);
|
||||
|
||||
linkedHashSet.removeIf(data -> data > 2);
|
||||
assertFalse(linkedHashSet.contains(3));
|
||||
assertFalse(linkedHashSet.contains(4));
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenRemovingAnElementWithIterator_shouldRemoveElement(){
|
||||
LinkedHashSet<Integer> linkedHashSet = new LinkedHashSet<>();
|
||||
linkedHashSet.add(0);
|
||||
linkedHashSet.add(1);
|
||||
linkedHashSet.add(2);
|
||||
|
||||
Iterator<Integer> iterator = linkedHashSet.iterator();
|
||||
int elementToRemove = 1;
|
||||
assertTrue(linkedHashSet.contains(elementToRemove));
|
||||
while(iterator.hasNext()){
|
||||
if(elementToRemove == iterator.next()){
|
||||
iterator.remove();
|
||||
}
|
||||
}
|
||||
assertFalse(linkedHashSet.contains(elementToRemove));
|
||||
}
|
||||
|
||||
}
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
package com.baeldung.treeset.collectintotreeset;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.math.RoundingMode;
|
||||
import java.util.Comparator;
|
||||
import java.util.TreeSet;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class CollectIntoTreeSetUnitTest {
|
||||
Player kai = new Player("Kai", 26, 28, 7);
|
||||
Player eric = new Player("Eric", 28, 30, 11);
|
||||
Player saajan = new Player("Saajan", 30, 100, 66);
|
||||
Player kevin = new Player("Kevin", 24, 50, 49);
|
||||
|
||||
@Test
|
||||
void givenAStream_whenCollectIntoTreeSetWithNaturalOrder_thenGetExpectedResult() {
|
||||
String kotlin = "Kotlin";
|
||||
String java = "Java";
|
||||
String python = "Python";
|
||||
String ruby = "Ruby";
|
||||
TreeSet<String> myTreeSet = Stream.of(ruby, java, kotlin, python)
|
||||
.collect(Collectors.toCollection(TreeSet::new));
|
||||
assertThat(myTreeSet).containsExactly(java, kotlin, python, ruby);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenAPlayerStream_whenCollectIntoTreeSet_thenGetExpectedResult() {
|
||||
TreeSet<Player> myTreeSet = Stream.of(saajan, eric, kai, kevin)
|
||||
.collect(Collectors.toCollection(TreeSet::new));
|
||||
assertThat(myTreeSet).containsExactly(kevin, kai, eric, saajan);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenAPlayerStream_whenCollectIntoTreeSetWithNoOfWinsComparator_thenGetExpectedResult() {
|
||||
TreeSet<Player> myTreeSet = Stream.of(saajan, eric, kai, kevin)
|
||||
.collect(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparingInt(Player::getNumberOfWins))));
|
||||
assertThat(myTreeSet).containsExactly(kai, eric, kevin, saajan);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenAPlayerStream_whenCollectIntoTreeSetWithWinRateComparator_thenGetExpectedResult() {
|
||||
TreeSet<Player> myTreeSet = Stream.of(saajan, eric, kai, kevin)
|
||||
.collect(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(player -> BigDecimal.valueOf(player.getNumberOfWins())
|
||||
.divide(BigDecimal.valueOf(player.getNumberOfPlayed()), 2, RoundingMode.HALF_UP)))));
|
||||
assertThat(myTreeSet).containsExactly(kai, eric, saajan, kevin);
|
||||
}
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
package com.baeldung.donerunnables;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class RunnableCompletionCheckerWithCompletableFuture {
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(RunnableCompletionCheckerWithCompletableFuture.class);
|
||||
private static final int NUMBER_OF_RUNNABLES = 5;
|
||||
private static final int PAUSE_MILLIS = 1000;
|
||||
|
||||
private static Runnable RUNNABLE = () -> {
|
||||
try {
|
||||
LOGGER.info("launching runnable");
|
||||
Thread.sleep(PAUSE_MILLIS);
|
||||
} catch (InterruptedException e) {
|
||||
}
|
||||
};
|
||||
|
||||
public static void main(String args[]) throws InterruptedException {
|
||||
List<Runnable> runnables = IntStream.range(0, NUMBER_OF_RUNNABLES)
|
||||
.mapToObj(x -> RUNNABLE)
|
||||
.collect(Collectors.toList());
|
||||
CompletableFuture<?>[] completableFutures = runAsynchronousTasks(runnables);
|
||||
LOGGER.info("Right after the creation of the completable future array, every completable future is done: {}", isEveryCompletableFutureDone(completableFutures));
|
||||
Thread.sleep((NUMBER_OF_RUNNABLES + 1) * PAUSE_MILLIS);
|
||||
LOGGER.info("After {} seconds, every completable future is done: {}", NUMBER_OF_RUNNABLES + 1, isEveryCompletableFutureDone(completableFutures));
|
||||
}
|
||||
|
||||
public static CompletableFuture<?>[] runAsynchronousTasks(List<Runnable> runnables) {
|
||||
return runnables.stream()
|
||||
.map(CompletableFuture::runAsync)
|
||||
.toArray(CompletableFuture<?>[]::new);
|
||||
}
|
||||
|
||||
public static boolean isEveryCompletableFutureDone(CompletableFuture<?>[] completableFutures) {
|
||||
return CompletableFuture.allOf(completableFutures)
|
||||
.isDone();
|
||||
}
|
||||
|
||||
}
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
package com.baeldung.donerunnables;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ThreadPoolExecutor;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class RunnableCompletionCheckerWithThreadPoolExecutor {
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(RunnableCompletionCheckerWithCompletableFuture.class);
|
||||
private static final int NUMBER_OF_RUNNABLES = 5;
|
||||
private static final int PAUSE_MILLIS = 1000;
|
||||
private static final int NUMBER_OF_THREADS = 5;
|
||||
|
||||
private static Runnable RUNNABLE = () -> {
|
||||
try {
|
||||
LOGGER.info("launching runnable");
|
||||
Thread.sleep(PAUSE_MILLIS);
|
||||
} catch (InterruptedException e) {
|
||||
}
|
||||
};
|
||||
|
||||
public static void main(String args[]) throws InterruptedException {
|
||||
List<Runnable> runnables = IntStream.range(0, NUMBER_OF_RUNNABLES)
|
||||
.mapToObj(x -> RUNNABLE)
|
||||
.collect(Collectors.toList());
|
||||
ThreadPoolExecutor executor = createThreadPoolExecutor(runnables);
|
||||
executor.shutdown();
|
||||
LOGGER.info("After a timeout of 0 seconds, every Runnable is done: {}", isEveryRunnableDone(executor, 0));
|
||||
Thread.sleep(100);
|
||||
LOGGER.info("After a timeout of 100 milliseconds, every Runnable is done: {}", isEveryRunnableDone(executor, 100));
|
||||
Thread.sleep(2000);
|
||||
LOGGER.info("After a timeout of 2 seconds, every Runnable is done: {}", isEveryRunnableDone(executor, 1500));
|
||||
}
|
||||
|
||||
public static ThreadPoolExecutor createThreadPoolExecutor(List<Runnable> runnables) {
|
||||
ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(NUMBER_OF_THREADS);
|
||||
runnables.forEach(executor::execute);
|
||||
return executor;
|
||||
}
|
||||
|
||||
public static boolean isEveryRunnableDone(ThreadPoolExecutor executor, int timeout) throws InterruptedException {
|
||||
return executor.awaitTermination(timeout, TimeUnit.MILLISECONDS);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -9,3 +9,4 @@
|
||||
- [Differences Between set() and lazySet() in Java Atomic Variables](https://www.baeldung.com/java-atomic-set-vs-lazyset)
|
||||
- [Volatile vs. Atomic Variables in Java](https://www.baeldung.com/java-volatile-vs-atomic)
|
||||
- [What Is “Locked Ownable Synchronizers” in Thread Dump?](https://www.baeldung.com/locked-ownable-synchronizers)
|
||||
- [Understanding java.lang.Thread.State: WAITING (parking)](https://www.baeldung.com/java-lang-thread-state-waiting-parking)
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user