Merge branch 'eugenp:master' into master

This commit is contained in:
Ulisses Lima
2022-08-25 16:55:26 -03:00
committed by GitHub
1428 changed files with 7208 additions and 3423 deletions
@@ -11,4 +11,5 @@ This module contains articles about algorithms. Some classes of algorithms, e.g.
- [Find the Longest Substring without Repeating Characters](https://www.baeldung.com/java-longest-substring-without-repeated-characters)
- [Permutations of an Array in Java](https://www.baeldung.com/java-array-permutations)
- [Find the Smallest Missing Integer in an Array](https://www.baeldung.com/java-smallest-missing-integer-in-array)
- [Permutations of a String in Java](https://www.baeldung.com/java-string-permutations)
- More articles: [[<-- prev]](/algorithms-miscellaneous-3) [[next -->]](/algorithms-miscellaneous-5)
@@ -1,14 +1,20 @@
package com.baeldung.algorithms.stringpermutation;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
public class ArrayHelper {
public class Helper {
private ArrayHelper() {
private Helper() {
}
static List<Character> toCharacterList(final String string) {
return string.chars().mapToObj(s -> ((char) s)).collect(Collectors.toList());
}
static String toString(Collection<Character> collection) {
return collection.stream().map(Object::toString).collect(Collectors.joining());
}
}
@@ -1,20 +1,29 @@
package com.baeldung.algorithms.stringpermutation;
import java.util.Collection;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.iterators.PermutationIterator;
public class StringPermutationsApache {
public Collection<List<Character>> eagerPermutationWithRepetitions(final String string) {
final List<Character> characters = ArrayHelper.toCharacterList(string);
return CollectionUtils.permutations(characters);
public List<String> eagerPermutationWithRepetitions(final String string) {
final List<Character> characters = Helper.toCharacterList(string);
return CollectionUtils.permutations(characters)
.stream()
.map(Helper::toString)
.collect(Collectors.toList());
}
public PermutationIterator<Character> lazyPermutationWithoutRepetitions(final String string) {
final List<Character> characters = ArrayHelper.toCharacterList(string);
return new PermutationIterator<>(characters);
public List<String> lazyPermutationWithoutRepetitions(final String string) {
final List<Character> characters = Helper.toCharacterList(string);
final PermutationIterator<Character> permutationIterator = new PermutationIterator<>(characters);
final List<String> result = new ArrayList<>();
while (permutationIterator.hasNext()) {
result.add(Helper.toString(permutationIterator.next()));
}
return result;
}
}
@@ -7,19 +7,21 @@ import org.paukov.combinatorics3.PermutationGenerator.TreatDuplicatesAs;
public class StringPermutationsCombinatoricsLib {
public List<List<Character>> permutationWithoutRepetitions(final String string) {
List<Character> chars = ArrayHelper.toCharacterList(string);
return Generator.permutation(chars)
.simple()
.stream()
.collect(Collectors.toList());
}
public List<String> permutationWithoutRepetitions(final String string) {
List<Character> chars = Helper.toCharacterList(string);
return Generator.permutation(chars)
.simple()
.stream()
.map(Helper::toString)
.collect(Collectors.toList());
}
public List<List<Character>> permutationWithRepetitions(final String string) {
List<Character> chars = ArrayHelper.toCharacterList(string);
public List<String> permutationWithRepetitions(final String string) {
List<Character> chars = Helper.toCharacterList(string);
return Generator.permutation(chars)
.simple(TreatDuplicatesAs.IDENTICAL)
.stream()
.map(Helper::toString)
.collect(Collectors.toList());
}
@@ -1,18 +1,22 @@
package com.baeldung.algorithms.stringpermutation;
import com.google.common.collect.Collections2;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
public class StringPermutationsGuava {
public Collection<List<Character>> permutationWithRepetitions(final String string) {
final List<Character> characters = ArrayHelper.toCharacterList(string);
return Collections2.permutations(characters);
public List<String> permutationWithRepetitions(final String string) {
final List<Character> characters = Helper.toCharacterList(string);
return Collections2.permutations(characters).stream()
.map(Helper::toString)
.collect(Collectors.toList());
}
public List<String> permutationWithoutRepetitions(final String string) {
final List<Character> characters = Helper.toCharacterList(string);
return Collections2.orderedPermutations(characters).stream()
.map(Helper::toString)
.collect(Collectors.toList());
}
public Collection<List<Character>> permutationWithoutRepetitions(final String string) {
final List<Character> characters = ArrayHelper.toCharacterList(string);
return Collections2.orderedPermutations(characters);
}
}
@@ -0,0 +1,36 @@
package com.baeldung.algorithms.stringpermutation;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
class HelperUnitTest {
@ParameterizedTest
@MethodSource("stringProvider")
void toListTest(String value, List<Character> expected) {
final List<Character> actual = Helper.toCharacterList(value);
assertThat(expected).isEqualTo(actual);
}
@ParameterizedTest
@MethodSource("stringProvider")
void toStringTest(String expected, List<Character> value) {
final String actual = Helper.toString(value);
assertThat(expected).isEqualTo(actual);
}
static Stream<Arguments> stringProvider() {
return Stream.of(
Arguments.of("hello", Arrays.asList('h', 'e', 'l', 'l', 'o')),
Arguments.of("abc", Arrays.asList('a','b','c')),
Arguments.of("12345", Arrays.asList('1', '2', '3', '4', '5'))
);
}
}
@@ -2,22 +2,19 @@ package com.baeldung.algorithms.stringpermutation;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Collection;
import java.util.List;
import org.apache.commons.collections4.iterators.PermutationIterator;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
class StringPermutationsApacheUnitTest {
@ParameterizedTest
@CsvSource({"abc, 6",
"hello, 120",
"aaaaaa, 720"})
@DisplayName("Apache permutation for ")
void testPermutationsWithRepetitions(String string, int numberOfPermutations) {
StringPermutationsApache permutationGenerator = new StringPermutationsApache();
final Collection<List<Character>> permutations = permutationGenerator.eagerPermutationWithRepetitions(string);
final List<String> permutations = permutationGenerator.eagerPermutationWithRepetitions(string);
final int size = permutations.size();
assertThat(permutations)
.as("\"%s\" should have %d permutation, but had %d", string, numberOfPermutations, size)
@@ -30,12 +27,8 @@ class StringPermutationsApacheUnitTest {
"aaaaaa, 720"})
void testPermutationsWithoutRepetitions(String string, int numberOfPermutations) {
StringPermutationsApache permutationGenerator = new StringPermutationsApache();
final PermutationIterator<Character> permutations = permutationGenerator.lazyPermutationWithoutRepetitions(string);
int size = 0;
while (permutations.hasNext()) {
permutations.next();
++size;
}
final List<String> permutations = permutationGenerator.lazyPermutationWithoutRepetitions(string);
int size = permutations.size();
assertThat(size)
.as("\"%s\" should have %d permutation, but had %d", string, numberOfPermutations, size)
.isEqualTo(numberOfPermutations);
@@ -14,7 +14,7 @@ class StringPermutationsCombinatoricsLibUnitTest {
"aaaaaa, 720"})
void testPermutationsWithRepetitions(String string, int numberOfPermutations) {
StringPermutationsCombinatoricsLib permutationGenerator = new StringPermutationsCombinatoricsLib();
final List<List<Character>> permutations = permutationGenerator.permutationWithRepetitions(string);
final List<String> permutations = permutationGenerator.permutationWithRepetitions(string);
final int size = permutations.size();
assertThat(permutations)
.as("\"%s\" should have %d permutation, but had %d", string, numberOfPermutations, size)
@@ -27,7 +27,7 @@ class StringPermutationsCombinatoricsLibUnitTest {
"aaaaaa, 1"})
void testPermutationsWithoutRepetitions(String string, int numberOfPermutations) {
StringPermutationsCombinatoricsLib permutationGenerator = new StringPermutationsCombinatoricsLib();
final List<List<Character>> permutations = permutationGenerator.permutationWithoutRepetitions(string);
final List<String> permutations = permutationGenerator.permutationWithoutRepetitions(string);
final int size = permutations.size();
assertThat(permutations)
.as("\"%s\" should have %d permutation, but had %d", string, numberOfPermutations, size)
@@ -2,7 +2,6 @@ package com.baeldung.algorithms.stringpermutation;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Collection;
import java.util.List;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
@@ -15,7 +14,7 @@ class StringPermutationsGuavaUnitTest {
"aaaaaa, 720"})
void testPermutationsWithRepetitions(String string, int numberOfPermutations) {
StringPermutationsGuava permutationGenerator = new StringPermutationsGuava();
final Collection<List<Character>> permutations = permutationGenerator.permutationWithRepetitions(string);
final List<String> permutations = permutationGenerator.permutationWithRepetitions(string);
final int size = permutations.size();
assertThat(permutations)
.as("\"%s\" should have %d permutation, but had %d", string, numberOfPermutations, size)
@@ -28,7 +27,7 @@ class StringPermutationsGuavaUnitTest {
"aaaaaa, 1"})
void testPermutationsWithoutRepetitions(String string, int numberOfPermutations) {
StringPermutationsGuava permutationGenerator = new StringPermutationsGuava();
final Collection<List<Character>> permutations = permutationGenerator.permutationWithoutRepetitions(string);
final List<String> permutations = permutationGenerator.permutationWithoutRepetitions(string);
final int size = permutations.size();
assertThat(permutations)
.as("\"%s\" should have %d permutation, but had %d", string, numberOfPermutations, size)
@@ -0,0 +1,4 @@
### Relevant Articles:
- [Algorithm to Identify and Validate a Credit Card Number](https://www.baeldung.com/java-validate-cc-number)
- More articles: [[<-- prev]](/algorithms-miscellaneous-6)
@@ -0,0 +1,16 @@
<?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>algorithms-miscellaneous-7</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>algorithms-miscellaneous-7</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>algorithms-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
</project>
@@ -0,0 +1,73 @@
package com.baeldung.algorithms.luhn;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class LuhnChecker {
private static final Logger LOGGER = LoggerFactory.getLogger(LuhnChecker.class);
/*
* Starting from the rightmost digit, we add all the digits together, performing
* a special step for every second digit.
*
* If the result is not divisible by 10, then the card number must not be valid.
*
* We can form a number that passes the Luhn Check by subtracting the result of
* the Luhn algorithm from 10.
*
* This is how the final digit of a credit card is calculated.
*/
public static boolean checkLuhn(String cardNumber) {
int sum = 0;
try {
for (int i = cardNumber.length() - 1; i >= 0; i--) {
int digit = Integer.parseInt(cardNumber.substring(i, i + 1));
if ((cardNumber.length() - i) % 2 == 0) {
digit = doubleAndSumDigits(digit);
}
sum += digit;
}
LOGGER.info("Luhn Algorithm sum of digits is " + sum);
} catch (NumberFormatException e) {
LOGGER.error("NumberFormatException - Card number probably contained some non-numeric characters, returning false");
return false;
} catch (NullPointerException e) {
LOGGER.error("Null pointer - Card number was probably null, returning false");
return false;
}
boolean result = sum % 10 == 0;
LOGGER.info("Luhn check result (sum divisible by 10): " + result);
return result;
}
/*
* We apply this method to every second number from the right of the card
* number. First, we double the digit, then we sum the digits.
*
* Note: subtracting 9 is equivalent to doubling and summing digits (when
* starting with a single digit) 0-4 -> produce single digit when doubled
* 5*2 = 10 -> 1+0 = 1 = 10-9
* 6*2 = 12 -> 1+3 = 3 = 12-9
* 7*2 = 14 -> 1+5 = 5 = 14-9
* 8*2 = 16 -> 1+7 = 7 = 16-9
* 9*2 = 18 -> 1+9 = 9 = 18-9
*/
public static int doubleAndSumDigits(int digit) {
int ret = digit * 2;
if (ret > 9) {
ret -= 9;
}
return ret;
}
}
@@ -0,0 +1,63 @@
package com.baeldung.algorithms.luhn;
import org.junit.Assert;
import org.junit.Test;
public class LuhnCheckerUnitTest {
@Test
public void whenCardNumberDoesMeetLuhnCriteria_thenCheckLuhnReturnsTrue() {
String cardNumber = "8649";
boolean result = LuhnChecker.checkLuhn(cardNumber);
Assert.assertTrue(result);
}
@Test
public void whenCardNumberDoesNotMeetLuhnCriteria_thenCheckLuhnReturnsFalse() {
String cardNumber = "8642";
boolean result = LuhnChecker.checkLuhn(cardNumber);
Assert.assertFalse(result);
}
@Test
public void whenCardNumberHasNoSecondDigits_thenCheckLuhnCalculatesCorrectly() {
String cardNumber = "0505050505050505";
boolean result = LuhnChecker.checkLuhn(cardNumber);
Assert.assertTrue(result);
}
@Test
public void whenCardNumberHasSecondDigits_thenCheckLuhnCalculatesCorrectly() {
String cardNumber = "75757575757575";
boolean result = LuhnChecker.checkLuhn(cardNumber);
Assert.assertTrue(result);
}
@Test
public void whenDoubleAndSumDigitsIsCalled_thenOutputIsCorrect() {
Assert.assertEquals(LuhnChecker.doubleAndSumDigits(0), 0);
Assert.assertEquals(LuhnChecker.doubleAndSumDigits(1), 2);
Assert.assertEquals(LuhnChecker.doubleAndSumDigits(2), 4);
Assert.assertEquals(LuhnChecker.doubleAndSumDigits(3), 6);
Assert.assertEquals(LuhnChecker.doubleAndSumDigits(4), 8);
Assert.assertEquals(LuhnChecker.doubleAndSumDigits(5), 1);
Assert.assertEquals(LuhnChecker.doubleAndSumDigits(6), 3);
Assert.assertEquals(LuhnChecker.doubleAndSumDigits(7), 5);
Assert.assertEquals(LuhnChecker.doubleAndSumDigits(8), 7);
Assert.assertEquals(LuhnChecker.doubleAndSumDigits(9), 9);
}
@Test
public void whenCardNumberNonNumeric_thenCheckLuhnReturnsFalse() {
String cardNumber = "test";
boolean result = LuhnChecker.checkLuhn(cardNumber);
Assert.assertFalse(result);
}
@Test
public void whenCardNumberIsNull_thenCheckLuhnReturnsFalse() {
String cardNumber = null;
boolean result = LuhnChecker.checkLuhn(cardNumber);
Assert.assertFalse(result);
}
}
+1
View File
@@ -21,6 +21,7 @@
<module>algorithms-miscellaneous-4</module>
<module>algorithms-miscellaneous-5</module>
<module>algorithms-miscellaneous-6</module>
<module>algorithms-miscellaneous-7</module>
<module>algorithms-searching</module>
<module>algorithms-sorting</module>
<module>algorithms-sorting-2</module>
+1 -1
View File
@@ -5,7 +5,7 @@
<modelVersion>4.0.0</modelVersion>
<artifactId>apache-cxf-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>apache-cxf</name>
<name>apache-cxf-modules</name>
<packaging>pom</packaging>
<parent>
+9
View File
@@ -0,0 +1,9 @@
## Apache Kafka
This module contains articles about Apache Kafka.
##### Building the project
You can build the project from the command line using: *mvn clean install*, or in an IDE.
### Relevant Articles:
- [Guide to Check if Apache Kafka Server Is Running](https://www.baeldung.com/apache-kafka-check-server-is-running)
+1
View File
@@ -0,0 +1 @@
log4j.rootLogger=INFO, stdout
+68
View File
@@ -0,0 +1,68 @@
<?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>apache-kafka-2</artifactId>
<name>apache-kafka-2</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.apache.kafka</groupId>
<artifactId>kafka-clients</artifactId>
<version>${kafka.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>kafka</artifactId>
<version>${testcontainers-kafka.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>junit-jupiter</artifactId>
<version>${testcontainers-jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>net.java.dev.jna</groupId>
<artifactId>jna</artifactId>
<version>5.7.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
<scope>provided</scope>
</dependency>
</dependencies>
<properties>
<kafka.version>2.8.0</kafka.version>
<testcontainers-kafka.version>1.15.3</testcontainers-kafka.version>
<testcontainers-jupiter.version>1.15.3</testcontainers-jupiter.version>
</properties>
</project>
@@ -0,0 +1,35 @@
package com.baeldung.kafka;
import java.util.Collection;
import java.util.Properties;
import java.util.concurrent.ExecutionException;
import org.apache.kafka.clients.admin.AdminClient;
import org.apache.kafka.common.Node;
public class KafkaAdminClient {
private final AdminClient client;
public KafkaAdminClient(String bootstrap) {
Properties props = new Properties();
props.put("bootstrap.servers", bootstrap);
props.put("request.timeout.ms", 3000);
props.put("connections.max.idle.ms", 5000);
this.client = AdminClient.create(props);
}
public boolean verifyConnection() throws ExecutionException, InterruptedException {
Collection<Node> nodes = this.client.describeCluster()
.nodes()
.get();
return nodes != null && nodes.size() > 0;
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
String defaultBootStrapServer = "localhost:9092";
KafkaAdminClient kafkaAdminClient = new KafkaAdminClient(defaultBootStrapServer);
System.out.println(kafkaAdminClient.verifyConnection());
}
}
@@ -0,0 +1,39 @@
package com.baeldung.kafka;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.testcontainers.containers.KafkaContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import org.testcontainers.utility.DockerImageName;
import static org.assertj.core.api.Assertions.assertThat;
// This live test needs a running Docker instance so that a kafka container can be created
@Testcontainers
class KafkaConnectionLiveTest {
@Container
private static final KafkaContainer KAFKA_CONTAINER = new KafkaContainer(DockerImageName.parse("confluentinc/cp-kafka:5.4.3"));
private KafkaAdminClient kafkaAdminClient;
@BeforeEach
void setup() {
KAFKA_CONTAINER.addExposedPort(9092);
this.kafkaAdminClient = new KafkaAdminClient(KAFKA_CONTAINER.getBootstrapServers());
}
@AfterEach
void destroy() {
KAFKA_CONTAINER.stop();
}
@Test
void givenKafkaIsRunning_whenCheckedForConnection_thenConnectionIsVerified() throws Exception {
boolean alive = kafkaAdminClient.verifyConnection();
assertThat(alive).isTrue();
}
}
-1
View File
@@ -173,7 +173,6 @@
<graphframes.version>0.8.1-spark3.0-s_2.12</graphframes.version>
<com.datastax.spark.spark-cassandra-connector.version>2.5.2</com.datastax.spark.spark-cassandra-connector.version>
<com.datastax.spark.spark-cassandra-connector-java.version>1.6.0-M1</com.datastax.spark.spark-cassandra-connector-java.version>
<lombok.version>1.18.20</lombok.version>
</properties>
</project>
@@ -1,16 +1,19 @@
server:
port: 8080
spring:
jersey:
application-path: /odata
jpa:
defer-datasource-initialization: true
show-sql: true
open-in-view: false
hibernate:
ddl-auto: update
properties:
hibernate:
globally_quoted_identifiers: true
sql:
init:
+8 -10
View File
@@ -1,12 +1,10 @@
insert into car_maker(id,name) values (1,'Special Motors');
insert into car_maker(id,name) values (2,'BWM');
insert into car_maker(id,name) values (3,'Dolores');
insert into "car_maker"("id", "name") values (1,'Special Motors');
insert into "car_maker"("id", "name") values (2,'BWM');
insert into "car_maker"("id", "name") values (3,'Dolores');
insert into car_model(id,maker_fk,name,sku,year) values(1,1,'Muze','SM001',2018);
insert into car_model(id,maker_fk,name,sku,year) values(2,1,'Empada','SM002',2008);
insert into "car_model"("id", "maker_fk", "name", "sku", "year") values(1,1,'Muze','SM001',2018);
insert into "car_model"("id", "maker_fk", "name", "sku", "year") values(2,1,'Empada','SM002',2008);
insert into car_model(id,maker_fk,name,sku,year) values(4,2,'BWM-100','BWM100',2008);
insert into car_model(id,maker_fk,name,sku,year) values(5,2,'BWM-200','BWM200',2009);
insert into car_model(id,maker_fk,name,sku,year) values(6,2,'BWM-300','BWM300',2008);
alter sequence hibernate_sequence restart with 100;
insert into "car_model"("id", "maker_fk", "name", "sku", "year") values(4,2,'BWM-100','BWM100',2008);
insert into "car_model"("id", "maker_fk", "name", "sku", "year") values(5,2,'BWM-200','BWM200',2009);
insert into "car_model"("id", "maker_fk", "name", "sku", "year") values(6,2,'BWM-300','BWM300',2008);
@@ -8,4 +8,5 @@ This module contains articles about the Java List collection
- [Sort a List Alphabetically in Java](https://www.baeldung.com/java-sort-list-alphabetically)
- [Arrays.asList() vs Collections.singletonList()](https://www.baeldung.com/java-aslist-vs-singletonlist)
- [Replace Element at a Specific Index in a Java ArrayList](https://www.baeldung.com/java-arraylist-replace-at-index)
- [Difference Between Arrays.asList() and List.of()](https://www.baeldung.com/java-arrays-aslist-vs-list-of)
- [[<-- Prev]](/core-java-modules/core-java-collections-list-3)
@@ -64,6 +64,23 @@
<colt.version>1.2.0</colt.version>
<apache-commons.version>3.0</apache-commons.version>
<assertj.version>3.22.0</assertj.version>
<maven.compiler.source.version>17</maven.compiler.source.version>
<maven.compiler.target.version>17</maven.compiler.target.version>
</properties>
<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.version}</source>
<target>${maven.compiler.target.version}</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
</project>
@@ -0,0 +1,56 @@
package com.baeldung.list.creation;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
class ArraysAsListUnitTest {
@Test
void givenAnArrayOfIntegersWhenCreatingAListUsingArraysAsListThenItWillHaveTheSameElementsInTheSameOrder() {
Integer[] array = new Integer[]{1, 2, 3, 4};
List<Integer> list = Arrays.asList(array);
assertThat(list).containsExactly(1, 2, 3, 4);
}
@Test
void givenAnListOfIntegersCreatedUsingArraysAsListWhenChangingTheOriginalArrayTheReturnListWillAlsoChange() {
Integer[] array = new Integer[]{1, 2, 3};
List<Integer> list = Arrays.asList(array);
array[0] = 1000;
assertThat(list.get(0)).isEqualTo(1000);
}
@Test
void givenAnListOfIntegersCreatedUsingArraysAsListWhenChangingTheReturnedListTheOriginalArrayWillAlsoChange() {
Integer[] array = new Integer[]{1, 2, 3};
List<Integer> list = Arrays.asList(array);
list.set(0, 1000);
assertThat(array[0]).isEqualTo(1000);
}
@Test
void givenAnArrayOfIntegersCreatedUsingArraysAsListWhenModifyingAnExistingElementThenModifyIt() {
List<Integer> list = Arrays.asList(1, 2, 3, 4);
list.set(1, 1000);
assertThat(list.get(1)).isEqualTo(1000);
}
@Test
void givenAnArrayCreatedWithArraysAsListWhenAddingANewElementThenUnsupportedOperationExceptionIsThrown() {
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
assertThrows(UnsupportedOperationException.class, () -> list.add(6));
}
@Test
void givenAnArrayCreatedWithArraysAsListWhenRemovingAnExistingElementThenUnsupportedOperationExceptionIsThrown() {
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
assertThrows(UnsupportedOperationException.class, () -> list.remove(1));
}
}
@@ -0,0 +1,51 @@
package com.baeldung.list.creation;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
class ListOfUnitTest {
@Test
void givenAnArrayOfStringWhenCreatingAListUsingItsValuesThenItWillHaveTheSameElementsInTheSameOrder() {
String[] array = new String[]{"one", "two", "three"};
List<String> list = List.of(array);
assertThat(list).containsExactly("one", "two", "three");
}
@Test
void givenAnListOfStringCreatedUsingListOfWhenChangingTheOriginalArrayTheReturnListWontChange() {
String[] array = new String[]{"one", "two", "three"};
List<String> list = List.of(array);
array[0] = "thousand";
assertThat(list.get(0)).isEqualTo("one");
}
@Test
void givenAnArrayCreatedWithListOfWhenAddingANewElementThenUnsupportedOperationExceptionIsThrown() {
List<String> list = List.of("one", "two", "three");
assertThrows(UnsupportedOperationException.class, () -> list.add("four"));
}
@Test
void givenAnArrayCreatedWithListOfWhenRemovingAnExistingElementThenUnsupportedOperationExceptionIsThrown() {
List<String> list = List.of("one", "two", "three");
assertThrows(UnsupportedOperationException.class, () -> list.remove("two"));
}
@Test
void givenAnArrayCreatedWithListOfWhenModifyingAnExistingElementThenUnsupportedOperationExceptionIsThrown() {
List<String> list = List.of("one", "two", "three");
assertThrows(UnsupportedOperationException.class, () -> list.set(1, "four"));
}
@Test
void givenAnArrayContainingNullElementWhenUsingItToCreateListThenNullPointerExceptionIsThrown() {
assertThrows(NullPointerException.class, () -> List.of("one", null, "two"));
}
}
@@ -4,7 +4,7 @@ import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class CountdownLatchResetExampleUnitTest {
public class CountdownLatchResetExampleManualTest {
@Test
public void whenCountDownLatch_noReset() {
@@ -8,3 +8,4 @@
- [Acquire a Lock by a Key in Java](https://www.baeldung.com/java-acquire-lock-by-key)
- [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)

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