Merge pull request #18 from eugenp/master

Merge Sync up
This commit is contained in:
vatsalgosar 2021-02-20 19:13:07 +05:30 committed by GitHub
commit 23e368fc28
2913 changed files with 27255 additions and 23432 deletions

View File

@ -1,5 +1,3 @@
**UPDATE**: The price of "Learn Spring Security OAuth" will permanently change on the 11th of December, along with the upcoming OAuth2 material: http://bit.ly/github-lss
The Courses
==============================

View File

@ -5,6 +5,6 @@ This module contains articles about genetic algorithms.
### Relevant articles:
- [Introduction to Jenetics Library](https://www.baeldung.com/jenetics)
- [Ant Colony Optimization](https://www.baeldung.com/java-ant-colony-optimization)
- [Ant Colony Optimization with a Java Example](https://www.baeldung.com/java-ant-colony-optimization)
- [Design a Genetic Algorithm in Java](https://www.baeldung.com/java-genetic-algorithm)
- [The Traveling Salesman Problem in Java](https://www.baeldung.com/java-simulated-annealing-for-traveling-salesman)

View File

@ -6,8 +6,8 @@ This module contains articles about algorithms. Some classes of algorithms, e.g.
### Relevant articles:
- [Validating Input With Finite Automata in Java](https://www.baeldung.com/java-finite-automata)
- [Example of Hill Climbing Algorithm](https://www.baeldung.com/java-hill-climbing-algorithm)
- [Introduction to Minimax Algorithm](https://www.baeldung.com/java-minimax-algorithm)
- [Example of Hill Climbing Algorithm in Java](https://www.baeldung.com/java-hill-climbing-algorithm)
- [Introduction to Minimax Algorithm with a Java Implementation](https://www.baeldung.com/java-minimax-algorithm)
- [How to Calculate Levenshtein Distance in Java?](https://www.baeldung.com/java-levenshtein-distance)
- [How to Find the Kth Largest Element in Java](https://www.baeldung.com/java-kth-largest-element)
- More articles: [[next -->]](/../algorithms-miscellaneous-2)
- More articles: [[next -->]](/algorithms-miscellaneous-2)

View File

@ -14,4 +14,4 @@ This module contains articles about algorithms. Some classes of algorithms, e.g.
- [Displaying Money Amounts in Words](https://www.baeldung.com/java-money-into-words)
- [A Collaborative Filtering Recommendation System in Java](https://www.baeldung.com/java-collaborative-filtering-recommendations)
- [Implementing A* Pathfinding in Java](https://www.baeldung.com/java-a-star-pathfinding)
- More articles: [[<-- prev]](/../algorithms-miscellaneous-1) [[next -->]](/../algorithms-miscellaneous-3)
- More articles: [[<-- prev]](/algorithms-miscellaneous-1) [[next -->]](/algorithms-miscellaneous-3)

View File

@ -5,8 +5,8 @@ This module contains articles about algorithms. Some classes of algorithms, e.g.
### Relevant articles:
- [Multi-Swarm Optimization Algorithm in Java](https://www.baeldung.com/java-multi-swarm-algorithm)
- [Check If a String Contains All The Letters of The Alphabet](https://www.baeldung.com/java-string-contains-all-letters)
- [Find the Middle Element of a Linked List](https://www.baeldung.com/java-linked-list-middle-element)
- [Check If a String Contains All The Letters of The Alphabet with Java](https://www.baeldung.com/java-string-contains-all-letters)
- [Find the Middle Element of a Linked List in Java](https://www.baeldung.com/java-linked-list-middle-element)
- [Find Substrings That Are Palindromes in Java](https://www.baeldung.com/java-palindrome-substrings)
- [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)

View File

@ -9,11 +9,11 @@ This module contains articles about algorithms. Some classes of algorithms, e.g.
- [Reversing a Binary Tree in Java](https://www.baeldung.com/java-reversing-a-binary-tree)
- [Find If Two Numbers Are Relatively Prime in Java](https://www.baeldung.com/java-two-relatively-prime-numbers)
- [Knapsack Problem Implementation in Java](https://www.baeldung.com/java-knapsack)
- [How to Determine if a Binary Tree is Balanced](https://www.baeldung.com/java-balanced-binary-tree)
- [How to Determine if a Binary Tree is Balanced in Java](https://www.baeldung.com/java-balanced-binary-tree)
- [Overview of Combinatorial Problems in Java](https://www.baeldung.com/java-combinatorial-algorithms)
- [Prims Algorithm](https://www.baeldung.com/java-prim-algorithm)
- [Maximum Subarray Problem](https://www.baeldung.com/java-maximum-subarray)
- [How to Merge Two Sorted Arrays](https://www.baeldung.com/java-merge-sorted-arrays)
- [Median of Stream of Integers using Heap](https://www.baeldung.com/java-stream-integers-median-using-heap)
- More articles: [[<-- prev]](/../algorithms-miscellaneous-4) [[next -->]](/../algorithms-miscellaneous-6)
- [Prims Algorithm with a Java Implementation](https://www.baeldung.com/java-prim-algorithm)
- [Maximum Subarray Problem in Java](https://www.baeldung.com/java-maximum-subarray)
- [How to Merge Two Sorted Arrays in Java](https://www.baeldung.com/java-merge-sorted-arrays)
- [Median of Stream of Integers using Heap in Java](https://www.baeldung.com/java-stream-integers-median-using-heap)
- More articles: [[<-- prev]](/algorithms-miscellaneous-4) [[next -->]](/algorithms-miscellaneous-6)

View File

@ -1,12 +1,13 @@
### Relevant Articles:
- [Boruvkas Algorithm for Minimum Spanning Trees](https://www.baeldung.com/java-boruvka-algorithm)
- [Boruvkas Algorithm for Minimum Spanning Trees in Java](https://www.baeldung.com/java-boruvka-algorithm)
- [Gradient Descent in Java](https://www.baeldung.com/java-gradient-descent)
- [Kruskals Algorithm for Spanning Trees](https://www.baeldung.com/java-spanning-trees-kruskal)
- [Kruskals Algorithm for Spanning Trees with a Java Implementation](https://www.baeldung.com/java-spanning-trees-kruskal)
- [Balanced Brackets Algorithm in Java](https://www.baeldung.com/java-balanced-brackets-algorithm)
- [Efficiently Merge Sorted Java Sequences](https://www.baeldung.com/java-merge-sorted-sequences)
- [Introduction to Greedy Algorithms with Java](https://www.baeldung.com/java-greedy-algorithms)
- [The Caesar Cipher in Java](https://www.baeldung.com/java-caesar-cipher)
- [Implementing a 2048 Solver in Java](https://www.baeldung.com/2048-java-solver)
- [Finding Top K Elements in an Array](https://www.baeldung.com/java-array-top-elements)
- More articles: [[<-- prev]](/../algorithms-miscellaneous-5)
- [Finding Top K Elements in a Java Array](https://www.baeldung.com/java-array-top-elements)
- [Reversing a Linked List in Java](https://www.baeldung.com/java-reverse-linked-list)
- More articles: [[<-- prev]](/algorithms-miscellaneous-5)

View File

@ -8,8 +8,8 @@ This module contains articles about searching algorithms.
- [Depth First Search in Java](https://www.baeldung.com/java-depth-first-search)
- [Interpolation Search in Java](https://www.baeldung.com/java-interpolation-search)
- [Breadth-First Search Algorithm in Java](https://www.baeldung.com/java-breadth-first-search)
- [String Search Algorithms for Large Texts](https://www.baeldung.com/java-full-text-search-algorithms)
- [Monte Carlo Tree Search for Tic-Tac-Toe Game](https://www.baeldung.com/java-monte-carlo-tree-search)
- [String Search Algorithms for Large Texts with Java](https://www.baeldung.com/java-full-text-search-algorithms)
- [Monte Carlo Tree Search for Tic-Tac-Toe Game in Java](https://www.baeldung.com/java-monte-carlo-tree-search)
- [Range Search Algorithm in Java](https://www.baeldung.com/java-range-search)
- [Fast Pattern Matching of Strings Using Suffix Tree](https://www.baeldung.com/java-pattern-matching-suffix-tree)
- [Find the Kth Smallest Element in Two Sorted Arrays](https://www.baeldung.com/java-kth-smallest-element-in-sorted-arrays)
- [Fast Pattern Matching of Strings Using Suffix Tree in Java](https://www.baeldung.com/java-pattern-matching-suffix-tree)
- [Find the Kth Smallest Element in Two Sorted Arrays in Java](https://www.baeldung.com/java-kth-smallest-element-in-sorted-arrays)

View File

@ -2,6 +2,6 @@
- [Sorting a String Alphabetically in Java](https://www.baeldung.com/java-sort-string-alphabetically)
- [Sorting Strings by Contained Numbers in Java](https://www.baeldung.com/java-sort-strings-contained-numbers)
- [How an In-Place Sorting Algorithm Works](https://www.baeldung.com/java-in-place-sorting)
- [Partitioning and Sorting Arrays with Many Repeated Entries](https://www.baeldung.com/java-sorting-arrays-with-repeated-entries)
- [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)
- More articles: [[<-- prev]](/algorithms-sorting)

View File

@ -129,6 +129,11 @@
<artifactId>zookeeper</artifactId>
<version>${zookeeper.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>

View File

@ -8,3 +8,4 @@ This module contains articles about Apache Spark
- [Building a Data Pipeline with Kafka, Spark Streaming and Cassandra](https://www.baeldung.com/kafka-spark-data-pipeline)
- [Machine Learning with Spark MLlib](https://www.baeldung.com/spark-mlib-machine-learning)
- [Introduction to Spark Graph Processing with GraphFrames](https://www.baeldung.com/spark-graph-graphframes)
- [Apache Spark: Differences between Dataframes, Datasets and RDDs](https://www.baeldung.com/java-spark-dataframe-dataset-rdd)

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,75 @@
package com.baeldung.differences.dataframe.dataset.rdd;
public class TouristData {
private String region;
private String country;
private String year;
private String series;
private Double value;
private String footnotes;
private String source;
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
public String getSeries() {
return series;
}
public void setSeries(String series) {
this.series = series;
}
public Double getValue() {
return value;
}
public void setValue(Double value) {
this.value = value;
}
public String getFootnotes() {
return footnotes;
}
public void setFootnotes(String footnotes) {
this.footnotes = footnotes;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
@Override
public String toString() {
return "TouristData [region=" + region + ", country=" + country + ", year=" + year + ", series=" + series + ", value=" + value + ", footnotes=" + footnotes + ", source=" + source + "]";
}
}

View File

@ -0,0 +1,67 @@
package com.baeldung.differences.rdd;
import static org.junit.Assert.assertEquals;
import java.util.List;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import scala.Tuple2;
public class ActionsUnitTest {
private static JavaRDD<String> tourists;
private static JavaSparkContext sc;
public static final String COMMA_DELIMITER = ",(?=([^\"]*\"[^\"]*\")*[^\"]*$)";
@BeforeClass
public static void init() {
SparkConf conf = new SparkConf().setAppName("reduce")
.setMaster("local[*]");
sc = new JavaSparkContext(conf);
tourists = sc.textFile("data/Tourist.csv").filter(line -> !line.startsWith("Region"));
}
@AfterClass
public static void cleanup() {
sc.close();
}
@Test
public void whenDistinctCount_thenReturnDistinctNumRecords() {
JavaRDD<String> countries = tourists.map(line -> {
String[] columns = line.split(COMMA_DELIMITER);
return columns[1];
})
.distinct();
Long numberOfCountries = countries.count();
System.out.println("Count: " + numberOfCountries);
assertEquals(Long.valueOf(220), numberOfCountries);
}
@Test
public void whenReduceByKeySum_thenTotalValuePerKey() {
JavaRDD<String> touristsExpenditure = tourists.filter(line -> line.split(COMMA_DELIMITER)[3].contains("expenditure"));
JavaPairRDD<String, Double> expenditurePairRdd = touristsExpenditure.mapToPair(line -> {
String[] columns = line.split(COMMA_DELIMITER);
return new Tuple2<>(columns[1], Double.valueOf(columns[6]));
});
List<Tuple2<String, Double>> totalByCountry = expenditurePairRdd.reduceByKey((x, y) -> x + y)
.collect();
System.out.println("Total per Country: " + totalByCountry);
for(Tuple2<String, Double> tuple : totalByCountry) {
if (tuple._1.equals("Mexico")) {
assertEquals(Double.valueOf(99164), tuple._2);
}
}
}
}

View File

@ -0,0 +1,74 @@
package com.baeldung.differences.rdd;
import static org.apache.spark.sql.functions.col;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import java.util.List;
import org.apache.spark.sql.DataFrameReader;
import org.apache.spark.sql.Dataset;
import org.apache.spark.sql.Row;
import org.apache.spark.sql.SparkSession;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
public class DataFrameUnitTest {
private static SparkSession session;
private static Dataset<Row> data;
@BeforeClass
public static void init() {
session = SparkSession.builder()
.appName("TouristDataFrameExample")
.master("local[*]")
.getOrCreate();
DataFrameReader dataFrameReader = session.read();
data = dataFrameReader.option("header", "true")
.csv("data/Tourist.csv");
}
@AfterClass
public static void cleanup() {
session.stop();
}
@Test
public void whenSelectSpecificColumns_thenColumnsFiltered() {
Dataset<Row> selectedData = data.select(col("country"), col("year"), col("value"));
selectedData.show();
List<String> resultList = Arrays.asList(selectedData.columns());
assertTrue(resultList.contains("country"));
assertTrue(resultList.contains("year"));
assertTrue(resultList.contains("value"));
assertFalse(resultList.contains("Series"));
}
@Test
public void whenFilteringByCountry_thenCountryRecordsSelected() {
Dataset<Row> filteredData = data.filter(col("country").equalTo("Mexico"));
filteredData.show();
filteredData.foreach(record -> {
assertEquals("Mexico", record.get(1));
});
}
@Test
public void whenGroupCountByCountry_thenContryTotalRecords() {
Dataset<Row> recordsPerCountry = data.groupBy(col("country"))
.count();
recordsPerCountry.show();
Dataset<Row> filteredData = recordsPerCountry.filter(col("country").equalTo("Sweden"));
assertEquals(new Long(12), filteredData.first()
.get(1));
}
}

View File

@ -0,0 +1,83 @@
package com.baeldung.differences.rdd;
import static org.apache.spark.sql.functions.col;
import static org.apache.spark.sql.functions.sum;
import static org.junit.Assert.assertEquals;
import org.apache.spark.api.java.function.FilterFunction;
import org.apache.spark.sql.DataFrameReader;
import org.apache.spark.sql.Dataset;
import org.apache.spark.sql.Encoders;
import org.apache.spark.sql.Row;
import org.apache.spark.sql.SparkSession;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import com.baeldung.differences.dataframe.dataset.rdd.TouristData;
public class DatasetUnitTest {
private static SparkSession session;
private static Dataset<TouristData> typedDataset;
@BeforeClass
public static void init() {
session = SparkSession.builder()
.appName("TouristDatasetExample")
.master("local[*]")
.getOrCreate();
DataFrameReader dataFrameReader = session.read();
Dataset<Row> data = dataFrameReader.option("header", "true")
.csv("data/Tourist.csv");
Dataset<Row> responseWithSelectedColumns = data.select(col("region"),
col("country"), col("year"), col("series"), col("value").cast("double"),
col("footnotes"), col("source"));
typedDataset = responseWithSelectedColumns.as(Encoders.bean(TouristData.class));
}
@AfterClass
public static void cleanup() {
session.stop();
}
@Test
public void whenFilteringByCountry_thenCountryRecordsSelected() {
Dataset<TouristData> selectedData = typedDataset
.filter((FilterFunction<TouristData>) record -> record.getCountry()
.equals("Norway"));
selectedData.show();
selectedData.foreach(record -> {
assertEquals("Norway", record.getCountry());
});
}
@Test
public void whenGroupCountByCountry_thenContryTotalRecords() {
Dataset<Row> countriesCount = typedDataset.groupBy(typedDataset.col("country"))
.count();
countriesCount.show();
assertEquals(Long.valueOf(220), Long.valueOf(countriesCount.count()));
}
@Test
public void whenFilteredByPropertyRange_thenRetreiveValidRecords() {
// Filter records with existing data for years between 2010 and 2017
typedDataset.filter((FilterFunction<TouristData>) record -> record.getYear() != null
&& (Long.valueOf(record.getYear()) > 2010 && Long.valueOf(record.getYear()) < 2017))
.show();
}
@Test
public void whenSumValue_thenRetreiveTotalValue() {
// Total tourist expenditure by country
typedDataset.filter((FilterFunction<TouristData>) record -> record.getValue() != null
&& record.getSeries()
.contains("expenditure"))
.groupBy("country")
.agg(sum("value"))
.show();
}
}

View File

@ -0,0 +1,63 @@
package com.baeldung.differences.rdd;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.apache.commons.lang3.StringUtils;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
public class TransformationsUnitTest {
public static final String COMMA_DELIMITER = ",(?=([^\"]*\"[^\"]*\")*[^\"]*$)";
private static JavaSparkContext sc;
private static JavaRDD<String> tourists;
@BeforeClass
public static void init() {
SparkConf conf = new SparkConf().setAppName("uppercaseCountries")
.setMaster("local[*]");
sc = new JavaSparkContext(conf);
tourists = sc.textFile("data/Tourist.csv")
.filter(line -> !line.startsWith("Region")); //filter header row
}
@AfterClass
public static void cleanup() {
sc.close();
}
@Test
public void whenMapUpperCase_thenCountryNameUppercased() {
JavaRDD<String> upperCaseCountries = tourists.map(line -> {
String[] columns = line.split(COMMA_DELIMITER);
return columns[1].toUpperCase();
})
.distinct();
upperCaseCountries.saveAsTextFile("data/output/uppercase.txt");
upperCaseCountries.foreach(country -> {
//replace non alphanumerical characters
country = country.replaceAll("[^a-zA-Z]", "");
assertTrue(StringUtils.isAllUpperCase(country));
});
}
@Test
public void whenFilterByCountry_thenShowRequestedCountryRecords() {
JavaRDD<String> touristsInMexico = tourists.filter(line -> line.split(COMMA_DELIMITER)[1].equals("Mexico"));
touristsInMexico.saveAsTextFile("data/output/touristInMexico.txt");
touristsInMexico.foreach(record -> {
assertEquals("Mexico", record.split(COMMA_DELIMITER)[1]);
});
}
}

View File

@ -51,7 +51,7 @@
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
<scope>provided</scope>
<exclusions>

View File

@ -89,7 +89,6 @@
<properties>
<json-simple.version>1.1.1</json-simple.version>
<commons-io.version>2.5</commons-io.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>
<gson.version>2.8.2</gson.version>

View File

@ -6,10 +6,12 @@ import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent;
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zaxxer.hikari.HikariDataSource;
import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
import java.util.HashMap;
import java.util.Map;
@ -22,11 +24,14 @@ import static org.hibernate.cfg.AvailableSettings.PASS;
*/
public class App implements RequestHandler<APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent> {
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
private SessionFactory sessionFactory = createSessionFactory();
public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent input, Context context) {
try (SessionFactory sessionFactory = createSessionFactory()) {
try {
ShippingService service = new ShippingService(sessionFactory, new ShippingDao());
return routeRequest(input, service);
} finally {
flushConnectionPool();
}
}
@ -105,4 +110,12 @@ private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
.buildMetadata()
.buildSessionFactory();
}
private void flushConnectionPool() {
ConnectionProvider connectionProvider = sessionFactory.getSessionFactoryOptions()
.getServiceRegistry()
.getService(ConnectionProvider.class);
HikariDataSource hikariDataSource = connectionProvider.unwrap(HikariDataSource.class);
hikariDataSource.getHikariPoolMXBean().softEvictConnections();
}
}

View File

@ -154,7 +154,6 @@
<properties>
<blade-mvc.version>2.0.14.RELEASE</blade-mvc.version>
<bootstrap.version>4.2.1</bootstrap.version>
<commons-lang3.version>3.8.1</commons-lang3.version>
<lombok.version>1.18.4</lombok.version>
<httpclient.version>4.5.6</httpclient.version>
<httpmime.version>4.5.6</httpmime.version>

View File

@ -5,8 +5,9 @@ This module contains articles about Java 10 core features
### Relevant Articles:
- [Java 10 LocalVariable Type-Inference](http://www.baeldung.com/java-10-local-variable-type-inference)
- [Guide to Java 10](http://www.baeldung.com/java-10-overview)
- [New Features in Java 10](https://www.baeldung.com/java-10-overview)
- [Copy a List to Another List in Java](http://www.baeldung.com/java-copy-list-to-another)
- [Deep Dive Into the New Java JIT Compiler Graal](https://www.baeldung.com/graal-java-jit-compiler)
- [Copying Sets in Java](https://www.baeldung.com/java-copy-sets)
- [Converting between a List and a Set in Java](https://www.baeldung.com/convert-list-to-set-and-set-to-list)
- [Java IndexOutOfBoundsException “Source Does Not Fit in Dest”](https://www.baeldung.com/java-indexoutofboundsexception)

View File

@ -6,3 +6,4 @@ This module contains articles about Java 11 core features
- [Guide to Java 8 Optional](https://www.baeldung.com/java-optional)
- [Guide to Java Reflection](http://www.baeldung.com/java-reflection)
- [Guide to Java 8s Collectors](https://www.baeldung.com/java-8-collectors)
- [New Features in Java 11](https://www.baeldung.com/java-11-new-features)

View File

@ -28,6 +28,29 @@
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mock-server</groupId>
<artifactId>mockserver-junit-jupiter</artifactId>
<version>${mockserver.version}</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit.jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-params</artifactId>
<version>${junit.jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit.jupiter.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
@ -48,7 +71,9 @@
<maven.compiler.source.version>11</maven.compiler.source.version>
<maven.compiler.target.version>11</maven.compiler.target.version>
<guava.version>29.0-jre</guava.version>
<junit.jupiter.version>5.7.0</junit.jupiter.version>
<assertj.version>3.17.2</assertj.version>
<mockserver.version>5.11.1</mockserver.version>
</properties>
</project>

View File

@ -0,0 +1,17 @@
package com.baeldung.features;
public class MainClass {
private static boolean mainPrivateMethod() {
return true;
}
public static class NestedClass {
boolean nestedPublicMethod() {
return mainPrivateMethod();
}
}
}

View File

@ -0,0 +1,54 @@
package com.baeldung.features;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.mockserver.integration.ClientAndServer;
import org.mockserver.model.HttpStatusCode;
import org.mockserver.socket.PortFactory;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockserver.integration.ClientAndServer.startClientAndServer;
class HttpClientIntegrationTest {
private static ClientAndServer mockServer;
private static int port;
@BeforeAll
static void startServer() {
port = PortFactory.findFreePort();
mockServer = startClientAndServer(port);
mockServer.when(new org.mockserver.model.HttpRequest().withMethod("GET"))
.respond(new org.mockserver.model.HttpResponse()
.withStatusCode(HttpStatusCode.OK_200.code())
.withBody("Hello from the server!"));
}
@AfterAll
static void stopServer() {
mockServer.stop();
}
@Test
void givenSampleHttpRequest_whenRequestIsSent_thenServerResponseIsReceived() throws IOException, InterruptedException {
HttpClient httpClient = HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_2)
.connectTimeout(Duration.ofSeconds(20))
.build();
HttpRequest httpRequest = HttpRequest.newBuilder()
.GET()
.uri(URI.create("http://localhost:" + port))
.build();
HttpResponse<String> httpResponse = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString());
assertThat(httpResponse.body()).isEqualTo("Hello from the server!");
}
}

View File

@ -0,0 +1,61 @@
package com.baeldung.features;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import javax.annotation.Nonnull;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
class JavaElevenFeaturesUnitTest {
@Test
void givenMultilineString_whenExtractingNonBlankStrippedLines_thenLinesAreReturned() {
String multilineString = "Baeldung helps \n \n developers \n explore Java.";
List<String> lines = multilineString.lines()
.filter(line -> !line.isBlank())
.map(String::strip)
.collect(Collectors.toList());
assertThat(lines).containsExactly("Baeldung helps", "developers", "explore Java.");
}
@Test
void givenTemporaryFile_whenReadingStringContent_thenContentIsReturned(@TempDir Path tempDir) throws IOException {
Path filePath = Files.writeString(Files.createTempFile(tempDir, "demo", ".txt"), "Sample text");
String fileContent = Files.readString(filePath);
assertThat(fileContent).isEqualTo("Sample text");
}
@Test
void givenSampleList_whenConvertingToArray_thenItemsRemainUnchanged() {
List<String> sampleList = Arrays.asList("Java", "Kotlin");
String[] sampleArray = sampleList.toArray(String[]::new);
assertThat(sampleArray).containsExactly("Java", "Kotlin");
}
@Test
void givenSampleList_whenConvertingToUppercaseString_thenUppercaseIsReturned() {
List<String> sampleList = Arrays.asList("Java", "Kotlin");
String resultString = sampleList.stream()
.map((@Nonnull var x) -> x.toUpperCase())
.collect(Collectors.joining(", "));
assertThat(resultString).isEqualTo("JAVA, KOTLIN");
}
@Test
void givenSampleList_whenExtractingNonBlankValues_thenOnlyNonBlanksAreReturned() {
List<String> sampleList = Arrays.asList("Java", "\n \n", "Kotlin", " ");
List<String> withoutBlanks = sampleList.stream()
.filter(Predicate.not(String::isBlank))
.collect(Collectors.toList());
assertThat(withoutBlanks).containsExactly("Java", "Kotlin");
}
}

View File

@ -0,0 +1,37 @@
package com.baeldung.features;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
class NestedClassesUnitTest {
@Test
public void giveNestedClass_whenCallingMainClassPrivateMethod_thenNoExceptionIsThrown() {
MainClass.NestedClass nestedInstance = new MainClass.NestedClass();
assertThat(nestedInstance.nestedPublicMethod()).isTrue();
}
@Test
public void giveNestedClass_whenCheckingNestmate_thenNestedClassIsReturned() {
assertThat(MainClass.class.isNestmateOf(MainClass.NestedClass.class)).isTrue();
}
@Test
public void giveNestedClass_whenCheckingNestHost_thenMainClassIsReturned() {
assertThat(MainClass.NestedClass.class.getNestHost()).isEqualTo(MainClass.class);
}
@Test
public void giveNestedClass_whenCheckingNestMembers_thenNestMembersAreReturned() {
Set<String> nestedMembers = Arrays.stream(MainClass.NestedClass.class.getNestMembers())
.map(Class::getName)
.collect(Collectors.toSet());
assertThat(nestedMembers).contains(MainClass.class.getName(), MainClass.NestedClass.class.getName());
}
}

View File

@ -64,7 +64,7 @@ public class HttpClientUnitTest {
.send(request, HttpResponse.BodyHandlers.ofString());
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_MOVED_PERM));
assertThat(response.body(), containsString("https://stackoverflow.com/"));
assertTrue(response.headers().map().get("location").stream().anyMatch("https://stackoverflow.com/"::equals));
}
@Test

View File

@ -18,6 +18,7 @@ import java.security.NoSuchAlgorithmException;
import java.time.Duration;
import org.junit.Test;
import org.junit.jupiter.api.Disabled;
public class HttpRequestUnitTest {
@ -48,7 +49,12 @@ public class HttpRequestUnitTest {
assertThat(response.version(), equalTo(HttpClient.Version.HTTP_2));
}
@Test
/*
* This test will fail as soon as the given URL returns a HTTP 2 response.
* Therefore, let's leave it commented out.
* */
@Test
@Disabled
public void shouldFallbackToHttp1_1WhenWebsiteDoesNotUseHttp2() throws IOException, InterruptedException, URISyntaxException, NoSuchAlgorithmException {
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("https://postman-echo.com/get"))

View File

@ -1,4 +1,4 @@
## Relevant Articles:
- [String API Updates in Java 12](https://www.baeldung.com/java12-string-api)
- [New Features in Java 12](https://www.baeldung.com/java-12-new-features)

View File

@ -0,0 +1,21 @@
package java.com.baeldung.newfeatures;
import org.junit.Test;
import java.text.NumberFormat;
import java.util.Locale;
import static org.junit.Assert.assertEquals;
public class CompactNumbersUnitTest {
@Test
public void givenNumber_thenCompactValues() {
NumberFormat likesShort = NumberFormat.getCompactNumberInstance(new Locale("en", "US"), NumberFormat.Style.SHORT);
likesShort.setMaximumFractionDigits(2);
assertEquals("2.59K", likesShort.format(2592));
NumberFormat likesLong = NumberFormat.getCompactNumberInstance(new Locale("en", "US"), NumberFormat.Style.LONG);
likesLong.setMaximumFractionDigits(2);
assertEquals("2.59 thousand", likesShort.format(2592));
}
}

View File

@ -0,0 +1,32 @@
package java.com.baeldung.newfeatures;
import org.junit.Test;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import static org.junit.Assert.assertEquals;
public class FileMismatchUnitTest {
@Test
public void givenIdenticalFiles_thenShouldNotFindMismatch() throws IOException {
Path filePath1 = Files.createTempFile("file1", ".txt");
Path filePath2 = Files.createTempFile("file2", ".txt");
Files.writeString(filePath1, "Java 12 Article");
Files.writeString(filePath2, "Java 12 Article");
long mismatch = Files.mismatch(filePath1, filePath2);
assertEquals(-1, mismatch);
}
@Test
public void givenDifferentFiles_thenShouldFindMismatch() throws IOException {
Path filePath3 = Files.createTempFile("file3", ".txt");
Path filePath4 = Files.createTempFile("file4", ".txt");
Files.writeString(filePath3, "Java 12 Article");
Files.writeString(filePath4, "Java 12 Tutorial");
long mismatch = Files.mismatch(filePath3, filePath4);
assertEquals(8, mismatch);
}
}

View File

@ -0,0 +1,15 @@
package java.com.baeldung.newfeatures;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class StringUnitTest {
@Test
public void givenString_thenRevertValue() {
String text = "Baeldung";
String transformed = text.transform(value -> new StringBuilder(value).reverse().toString());
assertEquals("gnudleaB", transformed);
}
}

View File

@ -0,0 +1,18 @@
package java.com.baeldung.newfeatures;
import org.junit.Test;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.junit.Assert.assertEquals;
public class TeeingCollectorUnitTest {
@Test
public void givenSetOfNumbers_thenCalculateAverage() {
double mean = Stream.of(1, 2, 3, 4, 5)
.collect(Collectors.teeing(Collectors.summingDouble(i -> i), Collectors.counting(), (sum, count) -> sum / count));
assertEquals(3.0, mean);
}
}

View File

@ -1,4 +1,4 @@
### Relevant articles:
- [Java Switch Statement](https://www.baeldung.com/java-switch)
- [New Java 13 Features](https://www.baeldung.com/java-13-new-features)
- [New Features in Java 13](https://www.baeldung.com/java-13-new-features)

View File

@ -10,3 +10,4 @@ This module contains articles about Java 14.
- [Helpful NullPointerExceptions in Java 14](https://www.baeldung.com/java-14-nullpointerexception)
- [Foreign Memory Access API in Java 14](https://www.baeldung.com/java-foreign-memory-access)
- [Java 14 Record Keyword](https://www.baeldung.com/java-record-keyword)
- [New Features in Java 14](https://www.baeldung.com/java-14-new-features)

View File

@ -44,6 +44,8 @@
<configuration>
<release>${maven.compiler.release}</release>
<compilerArgs>--enable-preview</compilerArgs>
<source>14</source>
<target>14</target>
</configuration>
</plugin>
<plugin>

View File

@ -0,0 +1,30 @@
package com.baeldung.java14.character;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
public class IsLetterOrAlphabetUnitTest {
@Test
public void givenACharacter_whenLetter_thenAssertIsLetterTrue() {
assertTrue(Character.isLetter(65));
}
@Test
public void givenACharacter_whenLetter_thenAssertIsAlphabeticTrue() {
assertTrue(Character.isAlphabetic(65));
}
@Test
public void givenACharacter_whenAlphabeticAndNotLetter_thenAssertIsLetterFalse() {
assertFalse(Character.isLetter(837));
}
@Test
public void givenACharacter_whenAlphabeticAndNotLetter_thenAssertIsAlphabeticTrue() {
assertTrue(Character.isAlphabetic(837));
}
}

View File

@ -0,0 +1,26 @@
package com.baeldung.java14.newfeatues;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class MultilineUnitTest {
@SuppressWarnings("preview")
String multiline = """
A quick brown fox jumps over a lazy dog; \
the lazy dog howls loudly.""";
@SuppressWarnings("preview")
String anotherMultiline = """
A quick brown fox jumps over a lazy dog;
the lazy dog howls loudly.""";
@Test
public void givenMultilineString_whenSlashUsed_thenNoNewLine() {
assertFalse(multiline.contains("\n"));
assertTrue(anotherMultiline.contains("\n"));
}
}

View File

@ -0,0 +1,38 @@
package com.baeldung.java14.newfeatues;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class RecordUnitTest {
@SuppressWarnings("preview")
public record User(int id, String password) {
};
private User user1 = new User(0, "UserOne");
@Test
public void givenRecord_whenObjInitialized_thenValuesCanBeFetchedWithGetters() {
assertEquals(0, user1.id());
assertEquals("UserOne", user1.password());
}
@Test
public void whenRecord_thenEqualsImplemented() {
User user2 = user1;
assertEquals(user1, user2);
}
@Test
public void whenRecord_thenToStringImplemented() {
assertTrue(user1.toString()
.contains("UserOne"));
}
}

View File

@ -0,0 +1,50 @@
package com.baeldung.java14.newfeatues;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class SwitchExprUnitTest {
@Test
public void givenDay_whenSunday_thenWeekend() {
assertTrue(isTodayHolidayInJava8("SUNDAY"));
assertTrue(isTodayHolidayInJava14("SUNDAY"));
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> isTodayHolidayInJava8("SOMEDAY"));
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> isTodayHolidayInJava14("SOMEDAY"));
}
private boolean isTodayHolidayInJava8(String day) {
boolean isTodayHoliday;
switch (day) {
case "MONDAY":
case "TUESDAY":
case "WEDNESDAY":
case "THURSDAY":
case "FRIDAY":
isTodayHoliday = false;
break;
case "SATURDAY":
case "SUNDAY":
isTodayHoliday = true;
break;
default:
throw new IllegalArgumentException("What's a " + day);
}
return isTodayHoliday;
}
private boolean isTodayHolidayInJava14(String day) {
return switch (day) {
case "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY" -> false;
case "SATURDAY", "SUNDAY" -> true;
default -> throw new IllegalArgumentException("What's a " + day);
};
}
}

View File

@ -0,0 +1 @@
--enable-preview

View File

@ -0,0 +1,7 @@
## Core Java 15
This module contains articles about Java 15.
### Relevant articles
- [Sealed Classes and Interfaces in Java 15](https://www.baeldung.com/java-sealed-classes-interfaces)

View File

@ -0,0 +1,76 @@
<?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-15</artifactId>
<name>core-java-15</name>
<packaging>jar</packaging>
<url>http://maven.apache.org</url>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<release>${maven.compiler.release}</release>
<compilerArgs>--enable-preview</compilerArgs>
<source>14</source>
<target>14</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${surefire.plugin.version}</version>
<configuration>
<argLine>--enable-preview</argLine>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<maven.compiler.release>15</maven.compiler.release>
<assertj.version>3.17.2</assertj.version>
<maven-compiler-plugin.version>3.8.1</maven-compiler-plugin.version>
<surefire.plugin.version>3.0.0-M3</surefire.plugin.version>
</properties>
</project>

View File

@ -0,0 +1,49 @@
package com.baeldung.sealed.alternative;
public class Vehicles {
abstract static class Vehicle {
private final String registrationNumber;
public Vehicle(String registrationNumber) {
this.registrationNumber = registrationNumber;
}
public String getRegistrationNumber() {
return registrationNumber;
}
}
public static final class Car extends Vehicle {
private final int numberOfSeats;
public Car(int numberOfSeats, String registrationNumber) {
super(registrationNumber);
this.numberOfSeats = numberOfSeats;
}
public int getNumberOfSeats() {
return numberOfSeats;
}
}
public static final class Truck extends Vehicle {
private final int loadCapacity;
public Truck(int loadCapacity, String registrationNumber) {
super(registrationNumber);
this.loadCapacity = loadCapacity;
}
public int getLoadCapacity() {
return loadCapacity;
}
}
}

View File

@ -0,0 +1,21 @@
package com.baeldung.sealed.classes;
public non-sealed class Car extends Vehicle implements Service {
private final int numberOfSeats;
public Car(int numberOfSeats, String registrationNumber) {
super(registrationNumber);
this.numberOfSeats = numberOfSeats;
}
public int getNumberOfSeats() {
return numberOfSeats;
}
@Override
public int getMaxServiceIntervalInMonths() {
return 12;
}
}

View File

@ -0,0 +1,11 @@
package com.baeldung.sealed.classes;
public sealed interface Service permits Car, Truck {
int getMaxServiceIntervalInMonths();
default int getMaxDistanceBetweenServicesInKilometers() {
return 100000;
}
}

View File

@ -0,0 +1,21 @@
package com.baeldung.sealed.classes;
public final class Truck extends Vehicle implements Service {
private final int loadCapacity;
public Truck(int loadCapacity, String registrationNumber) {
super(registrationNumber);
this.loadCapacity = loadCapacity;
}
public int getLoadCapacity() {
return loadCapacity;
}
@Override
public int getMaxServiceIntervalInMonths() {
return 18;
}
}

View File

@ -0,0 +1,15 @@
package com.baeldung.sealed.classes;
public abstract sealed class Vehicle permits Car, Truck {
protected final String registrationNumber;
public Vehicle(String registrationNumber) {
this.registrationNumber = registrationNumber;
}
public String getRegistrationNumber() {
return registrationNumber;
}
}

View File

@ -0,0 +1,14 @@
package com.baeldung.sealed.records;
public record Car(int numberOfSeats, String registrationNumber) implements Vehicle {
@Override
public String getRegistrationNumber() {
return registrationNumber;
}
public int getNumberOfSeats() {
return numberOfSeats;
}
}

View File

@ -0,0 +1,14 @@
package com.baeldung.sealed.records;
public record Truck(int loadCapacity, String registrationNumber) implements Vehicle {
@Override
public String getRegistrationNumber() {
return registrationNumber;
}
public int getLoadCapacity() {
return loadCapacity;
}
}

View File

@ -0,0 +1,7 @@
package com.baeldung.sealed.records;
public sealed interface Vehicle permits Car, Truck {
String getRegistrationNumber();
}

View File

@ -0,0 +1,15 @@
package com.baeldung.whatsnew.records;
/**
* Java record with a header indicating 2 fields.
*/
public record Person(String name, int age) {
/**
* Public constructor that does some basic validation.
*/
public Person {
if (age < 0) {
throw new IllegalArgumentException("Age cannot be negative");
}
}
}

View File

@ -0,0 +1,9 @@
package com.baeldung.whatsnew.sealedclasses;
import java.util.Date;
public non-sealed class Employee extends Person {
public Date getHiredDate() {
return new Date();
}
}

View File

@ -0,0 +1,4 @@
package com.baeldung.whatsnew.sealedclasses;
public final class Manager extends Person {
}

View File

@ -0,0 +1,21 @@
package com.baeldung.whatsnew.sealedclasses;
import java.util.Date;
public sealed class Person permits Employee, Manager {
/**
* Demonstration of pattern matching for instanceof
*
* @param person A Person object
* @return
*/
public static void patternMatchingDemo(Person person) {
if(person instanceof Employee employee) {
Date hiredDate = employee.getHiredDate();
}
if(person instanceof Employee employee && employee.getHiredDate() != null) {
Date hiredDate = employee.getHiredDate();
}
}
}

View File

@ -0,0 +1,76 @@
package com.baeldung.sealed.classes;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.lang.constant.ClassDesc;
public class VehicleUnitTest {
private static Vehicle car;
private static Vehicle truck;
@BeforeAll
public static void createInstances() {
car = new Car(5, "VZ500DA");
truck = new Truck(19000, "VZ600TA");
}
@Test
public void givenCar_whenUsingReflectionAPI_thenSuperClassIsSealed() {
Assertions.assertThat(car.getClass().isSealed()).isEqualTo(false);
Assertions.assertThat(car.getClass().getSuperclass().isSealed()).isEqualTo(true);
Assertions.assertThat(car.getClass().getSuperclass().permittedSubclasses())
.contains(ClassDesc.of(car.getClass().getCanonicalName()));
}
@Test
public void givenTruck_whenUsingReflectionAPI_thenSuperClassIsSealed() {
Assertions.assertThat(truck.getClass().isSealed()).isEqualTo(false);
Assertions.assertThat(truck.getClass().getSuperclass().isSealed()).isEqualTo(true);
Assertions.assertThat(truck.getClass().getSuperclass().permittedSubclasses())
.contains(ClassDesc.of(truck.getClass().getCanonicalName()));
}
@Test
public void givenCar_whenGettingPropertyTraditionalWay_thenNumberOfSeatsPropertyIsReturned() {
Assertions.assertThat(getPropertyTraditionalWay(car)).isEqualTo(5);
}
@Test
public void givenCar_whenGettingPropertyViaPatternMatching_thenNumberOfSeatsPropertyIsReturned() {
Assertions.assertThat(getPropertyViaPatternMatching(car)).isEqualTo(5);
}
@Test
public void givenTruck_whenGettingPropertyTraditionalWay_thenLoadCapacityIsReturned() {
Assertions.assertThat(getPropertyTraditionalWay(truck)).isEqualTo(19000);
}
@Test
public void givenTruck_whenGettingPropertyViaPatternMatching_thenLoadCapacityIsReturned() {
Assertions.assertThat(getPropertyViaPatternMatching(truck)).isEqualTo(19000);
}
private int getPropertyTraditionalWay(Vehicle vehicle) {
if (vehicle instanceof Car) {
return ((Car) vehicle).getNumberOfSeats();
} else if (vehicle instanceof Truck) {
return ((Truck) vehicle).getLoadCapacity();
} else {
throw new RuntimeException("Unknown instance of Vehicle");
}
}
private int getPropertyViaPatternMatching(Vehicle vehicle) {
if (vehicle instanceof Car car) {
return car.getNumberOfSeats();
} else if (vehicle instanceof Truck truck) {
return truck.getLoadCapacity();
} else {
throw new RuntimeException("Unknown instance of Vehicle");
}
}
}

View File

@ -0,0 +1,76 @@
package com.baeldung.sealed.records;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.lang.constant.ClassDesc;
public class VehicleUnitTest {
private static Vehicle car;
private static Vehicle truck;
@BeforeAll
public static void createInstances() {
car = new Car(4, "VZ500DA");
truck = new Truck(16000, "VZ600TA");
}
@Test
public void givenCar_whenUsingReflectionAPI_thenInterfaceIsSealed() {
Assertions.assertThat(car.getClass().isSealed()).isEqualTo(false);
Assertions.assertThat(car.getClass().getInterfaces()[0].isSealed()).isEqualTo(true);
Assertions.assertThat(car.getClass().getInterfaces()[0].permittedSubclasses())
.contains(ClassDesc.of(car.getClass().getCanonicalName()));
}
@Test
public void givenTruck_whenUsingReflectionAPI_thenInterfaceIsSealed() {
Assertions.assertThat(truck.getClass().isSealed()).isEqualTo(false);
Assertions.assertThat(truck.getClass().getInterfaces()[0].isSealed()).isEqualTo(true);
Assertions.assertThat(truck.getClass().getInterfaces()[0].permittedSubclasses())
.contains(ClassDesc.of(truck.getClass().getCanonicalName()));
}
@Test
public void givenCar_whenGettingPropertyTraditionalWay_thenNumberOfSeatsPropertyIsReturned() {
Assertions.assertThat(getPropertyTraditionalWay(car)).isEqualTo(4);
}
@Test
public void givenCar_whenGettingPropertyViaPatternMatching_thenNumberOfSeatsPropertyIsReturned() {
Assertions.assertThat(getPropertyViaPatternMatching(car)).isEqualTo(4);
}
@Test
public void givenTruck_whenGettingPropertyTraditionalWay_thenLoadCapacityIsReturned() {
Assertions.assertThat(getPropertyTraditionalWay(truck)).isEqualTo(16000);
}
@Test
public void givenTruck_whenGettingPropertyViaPatternMatching_thenLoadCapacityIsReturned() {
Assertions.assertThat(getPropertyViaPatternMatching(truck)).isEqualTo(16000);
}
private int getPropertyTraditionalWay(Vehicle vehicle) {
if (vehicle instanceof Car) {
return ((Car) vehicle).getNumberOfSeats();
} else if (vehicle instanceof Truck) {
return ((Truck) vehicle).getLoadCapacity();
} else {
throw new RuntimeException("Unknown instance of Vehicle");
}
}
private int getPropertyViaPatternMatching(Vehicle vehicle) {
if (vehicle instanceof Car car) {
return car.getNumberOfSeats();
} else if (vehicle instanceof Truck truck) {
return truck.getLoadCapacity();
} else {
throw new RuntimeException("Unknown instance of Vehicle");
}
}
}

View File

@ -19,12 +19,12 @@ public class StudentDbService implements StudentService {
}
public Student update(Student student) {
logger.log(Level.INFO, "Updating sutdent in DB...");
logger.log(Level.INFO, "Updating student in DB...");
return student;
}
public String delete(String registrationId) {
logger.log(Level.INFO, "Deleteing sutdent in DB...");
logger.log(Level.INFO, "Deleting student in DB...");
return registrationId;
}
}

View File

@ -2,8 +2,7 @@ package com.baeldung.java9.modules;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.*;
import static org.hamcrest.collection.IsEmptyCollection.empty;
import static org.junit.Assert.*;
@ -74,7 +73,6 @@ public class ModuleAPIUnitTest {
ModuleLayer javaBaseModuleLayer = javaBaseModule.getLayer();
assertTrue(javaBaseModuleLayer.configuration().findModule(JAVA_BASE_MODULE_NAME).isPresent());
assertThat(javaBaseModuleLayer.configuration().modules().size(), is(78));
assertTrue(javaBaseModuleLayer.parents().get(0).configuration().parents().isEmpty());
}
@ -108,8 +106,7 @@ public class ModuleAPIUnitTest {
.collect(Collectors.toSet());
assertThat(javaBaseRequires, empty());
assertThat(javaSqlRequires.size(), is(3));
assertThat(javaSqlRequiresNames, containsInAnyOrder("java.base", "java.xml", "java.logging"));
assertThat(javaSqlRequiresNames, hasItems("java.base", "java.xml", "java.logging"));
}
@Test
@ -127,16 +124,13 @@ public class ModuleAPIUnitTest {
@Test
public void givenModules_whenAccessingModuleDescriptorExports_thenExportsAreReturned() {
Set<Exports> javaBaseExports = javaBaseModule.getDescriptor().exports();
Set<Exports> javaSqlExports = javaSqlModule.getDescriptor().exports();
Set<String> javaSqlExportsSource = javaSqlExports.stream()
.map(Exports::source)
.collect(Collectors.toSet());
assertThat(javaBaseExports.size(), is(108));
assertThat(javaSqlExports.size(), is(3));
assertThat(javaSqlExportsSource, containsInAnyOrder("java.sql", "javax.transaction.xa", "javax.sql"));
assertThat(javaSqlExportsSource, hasItems("java.sql", "javax.sql"));
}
@Test
@ -144,7 +138,6 @@ public class ModuleAPIUnitTest {
Set<String> javaBaseUses = javaBaseModule.getDescriptor().uses();
Set<String> javaSqlUses = javaSqlModule.getDescriptor().uses();
assertThat(javaBaseUses.size(), is(34));
assertThat(javaSqlUses, contains("java.sql.Driver"));
}

View File

@ -4,7 +4,7 @@ This module contains articles about core Java features that have been introduced
### Relevant Articles:
- [Java 9 New Features](https://www.baeldung.com/new-java-9)
- [New Features in Java 9](https://www.baeldung.com/new-java-9)
- [Java 9 Variable Handles Demystified](http://www.baeldung.com/java-variable-handles)
- [Exploring the New HTTP Client in Java 9 and 11](http://www.baeldung.com/java-9-http-client)
- [Multi-Release Jar Files](https://www.baeldung.com/java-multi-release-jar)

View File

@ -47,12 +47,12 @@
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.11</version>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.7</version>
<version>${commons-io.version}</version>
</dependency>
</dependencies>

View File

@ -7,3 +7,4 @@ This module contains complete guides about arrays in Java
- [Guide to the java.util.Arrays Class](https://www.baeldung.com/java-util-arrays)
- [What is \[Ljava.lang.Object;?](https://www.baeldung.com/java-tostring-array)
- [Guide to ArrayStoreException](https://www.baeldung.com/java-arraystoreexception)
- [Creating a Generic Array in Java](https://www.baeldung.com/java-generic-array)

View File

@ -0,0 +1,30 @@
package com.baeldung.genericarrays;
import java.lang.reflect.Array;
public class MyStack<E> {
private E[] elements;
private int size = 0;
public MyStack(Class<E> clazz, int capacity) {
elements = (E[]) Array.newInstance(clazz, capacity);
}
public void push(E item) {
if (size == elements.length) {
throw new RuntimeException();
}
elements[size++] = item;
}
public E pop() {
if (size == 0) {
throw new RuntimeException();
}
return elements[--size];
}
public E[] getAllElements() {
return elements;
}
}

View File

@ -0,0 +1,24 @@
package com.baeldung.genericarrays;
import org.junit.Test;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import static org.junit.Assert.assertEquals;
public class ListToArrayUnitTest {
@Test
public void givenListOfItems_whenToArray_thenReturnArrayOfItems() {
List<String> items = new LinkedList<>();
items.add("first item");
items.add("second item");
String[] itemsAsArray = items.toArray(new String[0]);
assertEquals("first item", itemsAsArray[0]);
assertEquals("second item", itemsAsArray[1]);
}
}

View File

@ -0,0 +1,44 @@
package com.baeldung.genericarrays;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class MyStackUnitTest {
@Test
public void givenStackWithTwoItems_whenPop_thenReturnLastAdded() {
MyStack<String> myStack = new MyStack<>(String.class, 2);
myStack.push("hello");
myStack.push("example");
assertEquals("example", myStack.pop());
}
@Test (expected = RuntimeException.class)
public void givenStackWithFixedCapacity_whenExceedCapacity_thenThrowException() {
MyStack<Integer> myStack = new MyStack<>(Integer.class, 2);
myStack.push(100);
myStack.push(200);
myStack.push(300);
}
@Test(expected = RuntimeException.class)
public void givenStack_whenPopOnEmptyStack_thenThrowException() {
MyStack<Integer> myStack = new MyStack<>(Integer.class, 1);
myStack.push(100);
myStack.pop();
myStack.pop();
}
@Test
public void givenStackWithItems_whenGetAllElements_thenSizeShouldEqualTotal() {
MyStack<String> myStack = new MyStack<>(String.class, 2);
myStack.push("hello");
myStack.push("example");
String[] items = myStack.getAllElements();
assertEquals(2, items.length);
}
}

View File

@ -29,8 +29,6 @@
</dependencies>
<properties>
<commons-lang3.version>3.9</commons-lang3.version>
<assertj-core.version>3.10.0</assertj-core.version>
</properties>
</project>

View File

@ -68,11 +68,7 @@
<properties>
<shade.plugin.version>3.2.0</shade.plugin.version>
<commons-lang3.version>3.9</commons-lang3.version>
<jmh.version>1.19</jmh.version>
<assertj-core.version>3.10.0</assertj-core.version>
</properties>
</project>

View File

@ -76,12 +76,8 @@
<properties>
<shade.plugin.version>3.2.0</shade.plugin.version>
<commons-lang3.version>3.9</commons-lang3.version>
<guava.version>28.2-jre</guava.version>
<jmh.version>1.19</jmh.version>
<assertj-core.version>3.10.0</assertj-core.version>
</properties>
</project>

View File

@ -0,0 +1,6 @@
## Core Java Character
This module contains articles about Java Character Class
### Relevant Articles:
- [Character#isAlphabetic vs. Character#isLetter](https://www.baeldung.com/java-character-isletter-isalphabetic)

View File

@ -0,0 +1,42 @@
<?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-char</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-char</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.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>
</dependencies>
<properties>
<openjdk.jmh.version>1.19</openjdk.jmh.version>
<assertj.version>3.11.1</assertj.version>
</properties>
</project>

View File

@ -0,0 +1,38 @@
package com.baeldung.character;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertEquals;
public class CharacterGeneralCategoryTypeUnitTest {
@Test
public void givenACharacter_whenUpperCaseLetter_thenAssertTrue() {
assertEquals(Character.UPPERCASE_LETTER, Character.getType('U'));
}
@Test
public void givenACharacter_whenLowerCaseLetter_thenAssertTrue() {
assertEquals(Character.LOWERCASE_LETTER, Character.getType('u'));
}
@Test
public void givenACharacter_whenTitleCaseLetter_thenAssertTrue() {
assertEquals(Character.TITLECASE_LETTER, Character.getType('\u01f2'));
}
@Test
public void givenACharacter_whenModifierLetter_thenAssertTrue() {
assertEquals(Character.MODIFIER_LETTER, Character.getType('\u02b0'));
}
@Test
public void givenACharacter_whenOtherLetter_thenAssertTrue() {
assertEquals(Character.OTHER_LETTER, Character.getType('\u05d0'));
}
@Test
public void givenACharacter_whenLetterNumber_thenAssertTrue() {
assertEquals(Character.LETTER_NUMBER, Character.getType('\u2164'));
}
}

View File

@ -0,0 +1,49 @@
package com.baeldung.character;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
public class IsLetterOrAlphabetUnitTest {
@Test
public void givenACharacter_whenUpperCaseLetter_thenAssertIsAlphabeticTrue() {
assertTrue(Character.isAlphabetic('A'));
}
@Test
public void givenACharacter_whenTitleCaseLetter_thenAssertIsAlphabeticTrue() {
assertTrue(Character.isAlphabetic('\u01f2'));
}
@Test
public void givenACharacter_whenLowerCaseLetter_thenAssertIsLetterTrue() {
assertTrue(Character.isAlphabetic('a'));
}
@Test
public void givenACharacter_whenModifierLetter_thenAssertIsLetterTrue() {
assertTrue(Character.isAlphabetic('\u02b0'));
}
@Test
public void givenACharacter_whenLetter_thenAssertIsLetterTrue() {
assertTrue(Character.isLetter('a'));
}
@Test
public void givenACharacter_whenLetter_thenAssertIsAlphabeticTrue() {
assertTrue(Character.isAlphabetic('a'));
}
@Test
public void givenACharacter_whenAlphabeticAndNotLetter_thenAssertIsLetterFalse() {
assertFalse(Character.isLetter('\u2164'));
}
@Test
public void givenACharacter_whenAlphabeticAndNotLetter_thenAssertIsAlphabeticTrue() {
assertTrue(Character.isAlphabetic('\u2164'));
}
}

View File

@ -13,3 +13,5 @@
- [Quick Guide to the Java Stack](https://www.baeldung.com/java-stack)
- [Convert an Array of Primitives to a List](https://www.baeldung.com/java-primitive-array-to-list)
- [A Guide to BitSet in Java](https://www.baeldung.com/java-bitset)
- [Get the First Key and Value From a HashMap](https://www.baeldung.com/java-hashmap-get-first-entry)
- [Performance of removeAll() in a HashSet](https://www.baeldung.com/java-hashset-removeall-performance)

View File

@ -35,7 +35,7 @@
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.10</version>
<version>${commons-lang3.version}</version>
</dependency>
</dependencies>

View File

@ -33,11 +33,15 @@ public class HashSetBenchmark {
private List<Employee> employeeList1 = new ArrayList<>();
private Set<Employee> employeeSet2 = new HashSet<>();
private List<Employee> employeeList2 = new ArrayList<>();
private Set<Employee> employeeSet3 = new HashSet<>();
private Set<Employee> employeeSet4 = new HashSet<>();
private long set1Size = 60000;
private long list1Size = 50000;
private long set2Size = 50000;
private long list2Size = 60000;
private long set3Size = 50000;
private long set4Size = 60000;
@Setup(Level.Trial)
public void setUp() {
@ -57,6 +61,14 @@ public class HashSetBenchmark {
for (long i = 0; i < list2Size; i++) {
employeeList2.add(new Employee(i, RandomStringUtils.random(7, true, false)));
}
for (long i = 0; i < set3Size; i++) {
employeeSet3.add(new Employee(i, RandomStringUtils.random(7, true, false)));
}
for (long i = 0; i < set4Size; i++) {
employeeSet4.add(new Employee(i, RandomStringUtils.random(7, true, false)));
}
}
@ -71,6 +83,11 @@ public class HashSetBenchmark {
public boolean given_SizeOfHashsetSmallerThanSizeOfCollection_When_RemoveAllFromHashSet_Then_BadPerformance(MyState state) {
return state.employeeSet2.removeAll(state.employeeList2);
}
@Benchmark
public boolean given_SizeOfHashsetSmallerThanSizeOfAnotherHashSet_When_RemoveAllFromHashSet_Then_GoodPerformance(MyState state) {
return state.employeeSet3.removeAll(state.employeeSet4);
}
public static void main(String[] args) throws Exception {
Options options = new OptionsBuilder().include(HashSetBenchmark.class.getSimpleName())

View File

@ -0,0 +1,7 @@
=========
## Core Java Collections Cookbooks and Examples
### Relevant Articles:
- [ArrayList vs. LinkedList vs. HashMap in Java](https://www.baeldung.com/java-arraylist-vs-linkedlist-vs-hashmap)

View File

@ -0,0 +1,31 @@
<?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-4</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-collections-4</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<assertj.version>3.18.0</assertj.version>
</properties>
</project>

View File

@ -0,0 +1,30 @@
package com.baeldung.collections.comparation;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
public class ArrayListUnitTest {
@Test
void givenArrayList_whenItemAddedToSpecificIndex_thenItCanBeRetrieved() {
List<String> list = new ArrayList<>();
list.add("Daniel");
list.add(0, "Marko");
assertThat(list).hasSize(2);
assertThat(list.get(0)).isEqualTo("Marko");
}
@Test
void givenArrayList_whenItemRemovedViaIndex_thenListSizeIsReduced() {
List<String> list = new ArrayList<>(Arrays.asList("Daniel", "Marko"));
list.remove(1);
assertThat(list).hasSize(1);
assertThat(list).doesNotContain("Marko");
}
}

View File

@ -0,0 +1,31 @@
package com.baeldung.collections.comparation;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
public class HashMapUnitTest {
@Test
void givenHashMap_whenItemAddedByKey_thenItCanBeRetrieved() {
Map<String, String> map = new HashMap<>();
map.put("123456", "Daniel");
map.put("654321", "Marko");
assertThat(map.get("654321")).isEqualTo("Marko");
}
@Test
void givenHashMap_whenItemRemovedByKey_thenMapSizeIsReduced() {
Map<String, String> map = new HashMap<>();
map.put("123456", "Daniel");
map.put("654321", "Marko");
map.remove("654321");
assertThat(map).hasSize(1);
}
}

View File

@ -0,0 +1,41 @@
package com.baeldung.collections.comparation;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
public class LinkedListUnitTest {
@Test
void givenLinkedList_whenItemIsAppended_thenItCanBeRetrieved() {
LinkedList<String> list = new LinkedList<>();
list.addLast("Daniel");
list.addFirst("Marko");
assertThat(list).hasSize(2);
assertThat(list.getLast()).isEqualTo("Daniel");
}
@Test
void givenLinkedList_whenItemIsRemoved_thenListSizeIsReduced() {
LinkedList<String> list = new LinkedList<>(Arrays.asList("Daniel", "Marko", "David"));
list.removeFirst();
list.removeLast();
assertThat(list).hasSize(1);
assertThat(list).containsExactly("Marko");
}
@Test
void givenLinkedList_whenItemInserted_thenItCanBeRetrievedAndDeleted() {
LinkedList<String> list = new LinkedList<>();
list.push("Daniel");
list.push("Marko");
assertThat(list.poll()).isEqualTo("Marko");
assertThat(list).hasSize(1);
}
}

View File

@ -0,0 +1,32 @@
package com.baeldung.collections.comparation;
import static org.assertj.core.api.Assertions.*;
import org.junit.jupiter.api.Test;
import java.util.*;
class ListVsMapUnitTest {
@Test
void givenList_whenIteratingTroughValues_thenEachValueIsPresent() {
List<String> list = new ArrayList<>();
list.add("Daniel");
list.add("Marko");
for (String name : list) {
assertThat(name).isIn(list);
}
assertThat(list).containsExactly("Daniel", "Marko");
}
@Test
void givenMap_whenIteratingTroughValues_thenEachValueIsPresent() {
Map<Integer, String> map = new HashMap<>();
map.put(1, "Daniel");
map.put(2, "Marko");
for (String name : map.values()) {
assertThat(name).isIn(map.values());
}
assertThat(map.values()).containsExactlyInAnyOrder("Daniel", "Marko");
}
}

View File

@ -8,4 +8,4 @@ This module contains articles about the Java ArrayList collection
- [ClassCastException: Arrays$ArrayList cannot be cast to ArrayList](https://www.baeldung.com/java-classcastexception-arrays-arraylist)
- [Multi Dimensional ArrayList in Java](https://www.baeldung.com/java-multi-dimensional-arraylist)
- [Removing an Element From an ArrayList](https://www.baeldung.com/java-arraylist-remove-element)
- [The Capacity of an ArrayList vs the Size of an Array in Java](https://www.baeldung.com/java-list-capacity-array-size)

View File

@ -0,0 +1,20 @@
package com.baeldung.listcapacityvsarraysize;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
class ArrayCreatorUnitTest {
@Test
void whenSizeOfAnArrayIsNonZero_thenReturnNewArrayOfGivenSize() {
Integer[] array = new Integer[10];
assertEquals(10, array.length);
}
@Test
void whenSizeOfAnArrayIsLessThanZero_thenThrowException() {
assertThrows(NegativeArraySizeException.class, () -> { Integer[] array = new Integer[-1]; });
}
}

View File

@ -0,0 +1,27 @@
package com.baeldung.listcapacityvsarraysize;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import static org.junit.jupiter.api.Assertions.*;
class ArrayListCreatorUnitTest {
@Test
void givenValidCapacityOfList_whenCreateListInvoked_thenCreateNewArrayListWithGivenCapacity() {
ArrayList<Integer> list = new ArrayList<>(100);
assertNotNull(list);
}
@Test
void givenInvalidCapacityOfList_whenCreateListInvoked_thenThrowException() {
assertThrows(IllegalArgumentException.class, () -> new ArrayList<>(-1));
}
@Test
void givenValidCapacityOfList_whenCreateListInvoked_thenCreateNewArrayListWithSizeZero() {
assertEquals(0, new ArrayList<Integer>(100).size());
}
}

View File

@ -36,7 +36,6 @@
<properties>
<commons-collections4.version>4.1</commons-collections4.version>
<commons-lang3.version>3.8.1</commons-lang3.version>
<assertj.version>3.11.1</assertj.version>
</properties>

View File

@ -26,7 +26,7 @@ public class Product {
return tags;
}
public Product addTagsOfOtherProdcut(Product product) {
public Product addTagsOfOtherProduct(Product product) {
this.tags.addAll(product.getTags());
return this;
}
@ -100,11 +100,11 @@ public class Product {
HashMap<String, Product> productsByName = new HashMap<>();
Product eBike2 = new Product("E-Bike", "A bike with a battery");
eBike2.getTags().add("sport");
productsByName.merge("E-Bike", eBike2, Product::addTagsOfOtherProdcut);
productsByName.merge("E-Bike", eBike2, Product::addTagsOfOtherProduct);
//Prior to Java 8:
if(productsByName.containsKey("E-Bike")) {
productsByName.get("E-Bike").addTagsOfOtherProdcut(eBike2);
productsByName.get("E-Bike").addTagsOfOtherProduct(eBike2);
} else {
productsByName.put("E-Bike", eBike2);
}
@ -117,7 +117,7 @@ public class Product {
productsByName.compute("E-Bike", (k,v) -> {
if(v != null) {
return v.addTagsOfOtherProdcut(eBike2);
return v.addTagsOfOtherProduct(eBike2);
} else {
return eBike2;
}
@ -125,7 +125,7 @@ public class Product {
//Prior to Java 8:
if(productsByName.containsKey("E-Bike")) {
productsByName.get("E-Bike").addTagsOfOtherProdcut(eBike2);
productsByName.get("E-Bike").addTagsOfOtherProduct(eBike2);
} else {
productsByName.put("E-Bike", eBike2);
}

View File

@ -6,4 +6,6 @@ This module contains articles about Map data structures in Java.
- [Java TreeMap vs HashMap](https://www.baeldung.com/java-treemap-vs-hashmap)
- [Comparing Two HashMaps in Java](https://www.baeldung.com/java-compare-hashmaps)
- [The Map.computeIfAbsent() Method](https://www.baeldung.com/java-map-computeifabsent)
- [Collections.synchronizedMap vs. ConcurrentHashMap](https://www.baeldung.com/java-synchronizedmap-vs-concurrenthashmap)
- [Java HashMap Load Factor](https://www.baeldung.com/java-hashmap-load-factor)
- More articles: [[<-- prev]](/core-java-modules/core-java-collections-maps-2)

View File

@ -15,7 +15,16 @@
</parent>
<dependencies>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>${jmh-core.version}</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
</dependencies>
<properties>

View File

@ -0,0 +1,96 @@
package com.baeldung.map.concurrenthashmap;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Threads;
import org.openjdk.jmh.annotations.Warmup;
@Fork(5)
@Threads(10)
@Warmup(iterations = 5)
@State(Scope.Benchmark)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public class MapPerformanceComparison {
private int TEST_NO_ITEMS;
public static void main(String[] args) throws Exception {
org.openjdk.jmh.Main.main(args);
}
@Setup
public void setup() {
TEST_NO_ITEMS = 1000;
}
@Benchmark
public void randomReadAndWriteSynchronizedMap() {
Map<String, Integer> map = Collections.synchronizedMap(new HashMap<String, Integer>());
performReadAndWriteTest(map);
}
@Benchmark
public void randomReadAndWriteConcurrentHashMap() {
Map<String, Integer> map = new ConcurrentHashMap<>();
performReadAndWriteTest(map);
}
private void performReadAndWriteTest(final Map<String, Integer> map) {
for (int i = 0; i < TEST_NO_ITEMS; i++) {
Integer randNumber = (int) Math.ceil(Math.random() * TEST_NO_ITEMS);
map.get(String.valueOf(randNumber));
map.put(String.valueOf(randNumber), randNumber);
}
}
@Benchmark
public void randomWriteSynchronizedMap() {
Map<String, Integer> map = Collections.synchronizedMap(new HashMap<String, Integer>());
performWriteTest(map);
}
@Benchmark
public void randomWriteConcurrentHashMap() {
Map<String, Integer> map = new ConcurrentHashMap<>();
performWriteTest(map);
}
private void performWriteTest(final Map<String, Integer> map) {
for (int i = 0; i < TEST_NO_ITEMS; i++) {
Integer randNumber = (int) Math.ceil(Math.random() * TEST_NO_ITEMS);
map.put(String.valueOf(randNumber), randNumber);
}
}
@Benchmark
public void randomReadSynchronizedMap() {
Map<String, Integer> map = Collections.synchronizedMap(new HashMap<String, Integer>());
performReadTest(map);
}
@Benchmark
public void randomReadConcurrentHashMap() {
Map<String, Integer> map = new ConcurrentHashMap<>();
performReadTest(map);
}
private void performReadTest(final Map<String, Integer> map) {
for (int i = 0; i < TEST_NO_ITEMS; i++) {
Integer randNumber = (int) Math.ceil(Math.random() * TEST_NO_ITEMS);
map.get(String.valueOf(randNumber));
}
}
}

View File

@ -0,0 +1,39 @@
package com.baeldung.map.propertieshashmap;
import com.google.common.collect.Maps;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.stream.Collectors;
public class PropertiesToHashMapConverter {
@SuppressWarnings({"rawtypes", "unchecked"})
public static HashMap<String, String> typeCastConvert(Properties prop) {
Map step1 = prop;
Map<String, String> step2 = (Map<String, String>) step1;
return new HashMap<>(step2);
}
public static HashMap<String, String> loopConvert(Properties prop) {
HashMap<String, String> retMap = new HashMap<>();
for (Map.Entry<Object, Object> entry : prop.entrySet()) {
retMap.put(String.valueOf(entry.getKey()), String.valueOf(entry.getValue()));
}
return retMap;
}
public static HashMap<String, String> streamConvert(Properties prop) {
return prop.entrySet().stream().collect(
Collectors.toMap(
e -> String.valueOf(e.getKey()),
e -> String.valueOf(e.getValue()),
(prev, next) -> next, HashMap::new
));
}
public static HashMap<String, String> guavaConvert(Properties prop) {
return Maps.newHashMap(Maps.fromProperties(prop));
}
}

View File

@ -0,0 +1,70 @@
package com.baeldung.map.concurrenthashmap;
import java.util.Collections;
import java.util.ConcurrentModificationException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import org.junit.Assert;
import org.junit.Test;
public class ConcurrentModificationErrorUnitTest {
@Test(expected = ConcurrentModificationException.class)
public void whenRemoveAndAddOnHashMap_thenConcurrentModificationError() {
Map<Integer, String> map = new HashMap<>();
map.put(1, "baeldung");
map.put(2, "HashMap");
Map<Integer, String> synchronizedMap = Collections.synchronizedMap(map);
Iterator<Entry<Integer, String>> iterator = synchronizedMap.entrySet().iterator();
while (iterator.hasNext()) {
synchronizedMap.put(3, "Modification");
iterator.next();
}
}
@Test(expected = ConcurrentModificationException.class)
public void whenRemoveAndAddOnTreeMap_thenConcurrentModificationError() {
Map<Integer, String> map = new TreeMap<>();
map.put(1, "baeldung");
map.put(2, "HashMap");
Map<Integer, String> synchronizedMap = Collections.synchronizedMap(map);
Iterator<Entry<Integer, String>> iterator = synchronizedMap.entrySet().iterator();
while (iterator.hasNext()) {
synchronizedMap.put(3, "Modification");
iterator.next();
}
}
@Test(expected = ConcurrentModificationException.class)
public void whenRemoveAndAddOnLinkedHashMap_thenConcurrentModificationError() {
Map<Integer, String> map = new LinkedHashMap<>();
map.put(1, "baeldung");
map.put(2, "HashMap");
Map<Integer, String> synchronizedMap = Collections.synchronizedMap(map);
Iterator<Entry<Integer, String>> iterator = synchronizedMap.entrySet().iterator();
while (iterator.hasNext()) {
synchronizedMap.put(3, "Modification");
iterator.next();
}
}
@Test
public void whenRemoveAndAddOnConcurrentHashMap_thenNoError() {
Map<Integer, String> map = new ConcurrentHashMap<>();
map.put(1, "baeldung");
map.put(2, "HashMap");
Iterator<Entry<Integer, String>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
map.put(3, "Modification");
iterator.next();
}
Assert.assertEquals(3, map.size());
}
}

View File

@ -0,0 +1,73 @@
package com.baeldung.map.concurrenthashmap;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import org.junit.Assert;
import org.junit.Test;
public class NullAllowInMapUnitTest {
@Test
public void givenHashMapBackedSynchronizedMap_whenNullAsKey_thenNoError() {
Map<String, Integer> map = Collections
.synchronizedMap(new HashMap<String, Integer>());
map.put(null, 1);
Assert.assertTrue(map.get(null).equals(1));
}
@Test(expected = NullPointerException.class)
public void givenTreeMapBackedSynchronizedMap_whenNullAsKey_thenException() {
Map<String, Integer> map = Collections.synchronizedMap(new TreeMap<String, Integer>());
map.put(null, 1);
Assert.assertTrue(map.get(null).equals(1));
}
@Test
public void givenLinkedHashMapBackedSynchronizedMap_whenNullAsKey_thenNoError() {
Map<String, Integer> map = Collections
.synchronizedMap(new LinkedHashMap<String, Integer>());
map.put(null, 1);
Assert.assertTrue(map.get(null).equals(1));
}
@Test(expected = NullPointerException.class)
public void givenConcurrentHasMap_whenNullAsKey_thenException() {
Map<String, Integer> map = new ConcurrentHashMap<>();
map.put(null, 1);
}
@Test
public void givenHashMapBackedSynchronizedMap_whenNullAsValue_thenNoError() {
Map<String, Integer> map = Collections.synchronizedMap(new HashMap<String, Integer>());
map.put("1", null);
Assert.assertNull(map.get("1"));
}
@Test
public void givenTreeMapBackedSynchronizedMap_whenNullAsValue_thenNoError() {
Map<String, Integer> map = Collections.synchronizedMap(new TreeMap<String, Integer>());
map.put("1", null);
Assert.assertNull(map.get("1"));
}
@Test
public void givenLinkedHashMapBackedSynchronizedMap_whenNullAsValue_thenNoError() {
Map<String, Integer> map = Collections
.synchronizedMap(new LinkedHashMap<String, Integer>());
map.put("1", null);
Assert.assertNull(map.get("1"));
}
@Test(expected = NullPointerException.class)
public void givenConcurrentHasMap_whenNullAsValue_thenException() {
Map<String, Integer> map = new ConcurrentHashMap<>();
map.put("1", null);
}
}

View File

@ -0,0 +1,49 @@
package com.baeldung.map.hashmap.loadfactor;
import java.util.HashMap;
import java.util.Map;
import org.junit.Assert;
import org.junit.jupiter.api.Test;
public class HashMapLoadFactorUnitTest {
@Test
public void whenCreateMapWithDefaultParam_thenSucces() {
Map<String, String> mapWithDefaultParams = new HashMap<>();
mapWithDefaultParams.put("1", "one");
mapWithDefaultParams.put("2", "two");
mapWithDefaultParams.put("3", "three");
mapWithDefaultParams.put("4", "four");
mapWithDefaultParams.put("5", "five");
Assert.assertEquals(5, mapWithDefaultParams.size());
}
@Test
public void whenCreateMapWithInitialCapacity_thenSucces() {
Map<String, String> mapWithInitialCapacity = new HashMap<>(5);
mapWithInitialCapacity.put("1", "one");
mapWithInitialCapacity.put("2", "two");
mapWithInitialCapacity.put("3", "three");
Assert.assertEquals(3, mapWithInitialCapacity.size());
}
@Test
public void whenCreateMapWithInitialCapacityAndLF_thenSucces() {
Map<String, String> mapWithInitialCapacityAndLF = new HashMap<>(5, 0.5f);
mapWithInitialCapacityAndLF.put("1", "one");
mapWithInitialCapacityAndLF.put("2", "two");
mapWithInitialCapacityAndLF.put("3", "three");
mapWithInitialCapacityAndLF.put("4", "four");
mapWithInitialCapacityAndLF.put("5", "five");
mapWithInitialCapacityAndLF.put("6", "six");
mapWithInitialCapacityAndLF.put("7", "seven");
mapWithInitialCapacityAndLF.put("8", "eight");
mapWithInitialCapacityAndLF.put("9", "nine");
mapWithInitialCapacityAndLF.put("10", "ten");
Assert.assertEquals(10, mapWithInitialCapacityAndLF.size());
}
}

View File

@ -0,0 +1,192 @@
package com.baeldung.map.propertieshashmap;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Properties;
import static org.junit.jupiter.api.Assertions.*;
class PropertiesToHashMapConverterUnitTest {
private Properties properties;
private final static String propertyFileName = "toHashMap.properties";
@BeforeEach
public void setup() throws IOException {
properties = new Properties();
try (InputStream is = getClass().getClassLoader().getResourceAsStream(propertyFileName)) {
if (is != null) {
properties.load(is);
}
}
}
@Test
public void havingPropertiesLoaded_whenCheck_thenEquals() {
assertEquals(3, properties.size());
assertEquals("str_value", properties.get("property1"));
assertEquals("123", properties.get("property2"));
assertEquals("", properties.get("property3"));
}
@Test
public void whenPropertiesModified_thenTypeSafeIssues() {
compromiseProperties(properties);
assertEquals(5, properties.size());
assertNull(properties.getProperty("property4"));
assertNotEquals(String.class, properties.get("property4").getClass());
assertEquals(456, properties.get("property4"));
assertNull(properties.getProperty("5"));
assertNotEquals(String.class, properties.get(5).getClass());
assertEquals(10.11, properties.get(5));
}
@Test
public void havingNonModifiedProperties_whenTypeCastConvert_thenNoTypeSafeIssues() {
HashMap<String, String> hMap = PropertiesToHashMapConverter.typeCastConvert(properties);
assertEquals(3, hMap.size());
assertEquals(String.class, hMap.get("property1").getClass());
assertEquals(properties.get("property1"), hMap.get("property1"));
assertEquals(String.class, hMap.get("property2").getClass());
assertEquals(properties.get("property2"), hMap.get("property2"));
assertEquals(String.class, hMap.get("property3").getClass());
assertEquals(properties.get("property3"), hMap.get("property3"));
}
@Test
public void havingModifiedProperties_whenTypeCastConvert_thenClassCastException() {
compromiseProperties(properties);
HashMap<String, String> hMap = PropertiesToHashMapConverter.typeCastConvert(properties);
assertEquals(5, hMap.size());
assertThrows(ClassCastException.class, () -> {
String s = hMap.get("property4");
});
assertEquals(Integer.class, ((Object) hMap.get("property4")).getClass());
assertNull(hMap.get("5"));
assertNotNull(hMap.get(5));
assertThrows(ClassCastException.class, () -> {
String s = hMap.get(5);
});
assertEquals(Double.class, ((Object) hMap.get(5)).getClass());
}
@Test
public void havingNonModifiedProperties_whenLoopConvert_thenNoTypeSafeIssues() {
HashMap<String, String> hMap = PropertiesToHashMapConverter.loopConvert(properties);
assertEquals(3, hMap.size());
assertEquals(String.class, hMap.get("property1").getClass());
assertEquals(properties.get("property1"), hMap.get("property1"));
assertEquals(String.class, hMap.get("property2").getClass());
assertEquals(properties.get("property2"), hMap.get("property2"));
assertEquals(String.class, hMap.get("property3").getClass());
assertEquals(properties.get("property3"), hMap.get("property3"));
}
@Test
public void havingModifiedProperties_whenLoopConvert_thenNoClassCastException() {
compromiseProperties(properties);
HashMap<String, String> hMap = PropertiesToHashMapConverter.loopConvert(properties);
assertEquals(5, hMap.size());
assertDoesNotThrow(() -> {
String s = hMap.get("property4");
});
assertEquals(String.class, hMap.get("property4").getClass());
assertEquals("456", hMap.get("property4"));
assertDoesNotThrow(() -> {
String s = hMap.get("5");
});
assertEquals("10.11", hMap.get("5"));
}
@Test
public void havingNonModifiedProperties_whenStreamConvert_thenNoTypeSafeIssues() {
HashMap<String, String> hMap = PropertiesToHashMapConverter.streamConvert(properties);
assertEquals(3, hMap.size());
assertEquals(String.class, hMap.get("property1").getClass());
assertEquals(properties.get("property1"), hMap.get("property1"));
assertEquals(String.class, hMap.get("property2").getClass());
assertEquals(properties.get("property2"), hMap.get("property2"));
assertEquals(String.class, hMap.get("property3").getClass());
assertEquals(properties.get("property3"), hMap.get("property3"));
}
@Test
public void havingModifiedProperties_whenStreamConvert_thenNoClassCastException() {
compromiseProperties(properties);
HashMap<String, String> hMap = PropertiesToHashMapConverter.streamConvert(properties);
assertEquals(5, hMap.size());
assertDoesNotThrow(() -> {
String s = hMap.get("property4");
});
assertEquals(String.class, hMap.get("property4").getClass());
assertEquals("456", hMap.get("property4"));
assertDoesNotThrow(() -> {
String s = hMap.get("5");
});
assertEquals("10.11", hMap.get("5"));
}
@Test
public void havingModifiedProperties_whenLoopConvertAndStreamConvert_thenHashMapsSame() {
compromiseProperties(properties);
HashMap<String, String> hMap1 = PropertiesToHashMapConverter.loopConvert(properties);
HashMap<String, String> hMap2 = PropertiesToHashMapConverter.streamConvert(properties);
assertEquals(hMap2, hMap1);
}
@Test
public void havingNonModifiedProperties_whenGuavaConvert_thenNoTypeSafeIssues() {
HashMap<String, String> hMap = PropertiesToHashMapConverter.guavaConvert(properties);
assertEquals(3, hMap.size());
assertEquals(String.class, hMap.get("property1").getClass());
assertEquals(properties.get("property1"), hMap.get("property1"));
assertEquals(String.class, hMap.get("property2").getClass());
assertEquals(properties.get("property2"), hMap.get("property2"));
assertEquals(String.class, hMap.get("property3").getClass());
assertEquals(properties.get("property3"), hMap.get("property3"));
}
@Test
public void havingModifiedProperties_whenGuavaConvert_thenUnableToConvertAndThrowException() {
compromiseProperties(properties);
assertThrows(Exception.class, () -> PropertiesToHashMapConverter.guavaConvert(properties));
}
@Test
public void havingModifiedPropertiesWithNoIntegerValue_whenGuavaConvert_thenNullPointerException() {
properties.put("property4", 456);
assertThrows(NullPointerException.class, () -> PropertiesToHashMapConverter.guavaConvert(properties));
}
@Test
public void havingModifiedPropertiesWithNoIntegerKey_whenGuavaConvert_thenClassCastException() {
properties.put(5, 10.11);
assertThrows(ClassCastException.class, () -> PropertiesToHashMapConverter.guavaConvert(properties));
}
private void compromiseProperties(Properties prop) {
prop.put("property4", 456);
prop.put(5, 10.11);
}
}

View File

@ -0,0 +1,3 @@
property1=str_value
property2=123
property3=

View File

@ -10,11 +10,17 @@ import org.openjdk.jcstress.annotations.Outcome;
import org.openjdk.jcstress.annotations.State;
import org.openjdk.jcstress.infra.results.I_Result;
/**
* This is defined as a manual test because it tries to simulate the race conditions
* in a concurrent program that is poorly designed and hence may fail nondeterministically.
* This will help the CI jobs to ignore these tests and a developer to run them manually.
*
*/
@JCStressTest
@Outcome(id = "1", expect = ACCEPTABLE_INTERESTING, desc = "One update lost.")
@Outcome(id = "2", expect = ACCEPTABLE, desc = "Both updates.")
@State
public class MyCounterJCStressUnitTest {
public class MyCounterJCStressManualTest {
private MyCounter counter;

View File

@ -1,12 +1,17 @@
package com.baeldung.concurrent;
import org.junit.Ignore;
import org.junit.Test;
import edu.umd.cs.mtc.MultithreadedTestCase;
import edu.umd.cs.mtc.TestFramework;
public class MyCounterMultithreadedTCUnitTest extends MultithreadedTestCase {
/**
* This is defined as a manual test because it tries to simulate the race conditions
* in a concurrent program that is poorly designed and hence may fail nondeterministically.
* This will help the CI jobs to ignore these tests and a developer to run them manually.
*
*/
public class MyCounterMultithreadedTCManualTest extends MultithreadedTestCase {
private MyCounter counter;
@ -29,9 +34,8 @@ public class MyCounterMultithreadedTCUnitTest extends MultithreadedTestCase {
assertEquals(2, counter.getCount());
}
@Ignore
@Test
public void testCounter() throws Throwable {
TestFramework.runManyTimes(new MyCounterMultithreadedTCUnitTest(), 1000);
TestFramework.runManyTimes(new MyCounterMultithreadedTCManualTest(), 1000);
}
}

View File

@ -0,0 +1,63 @@
package com.baeldung.concurrent;
import static org.junit.Assert.assertEquals;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.junit.Test;
/**
* This is defined as a manual test because it tries to simulate the race conditions
* in a concurrent program that is poorly designed and hence may fail nondeterministically.
* This will help the CI jobs to ignore these tests and a developer to run them manually.
*
*/
public class MyCounterSimpleManualTest {
@Test
public void testCounter() {
MyCounter counter = new MyCounter();
for (int i = 0; i < 500; i++)
counter.increment();
assertEquals(500, counter.getCount());
}
@Test
public void testCounterWithConcurrency() throws InterruptedException {
int numberOfThreads = 100;
ExecutorService service = Executors.newFixedThreadPool(10);
CountDownLatch latch = new CountDownLatch(numberOfThreads);
MyCounter counter = new MyCounter();
for (int i = 0; i < numberOfThreads; i++) {
service.execute(() -> {
counter.increment();
latch.countDown();
});
}
latch.await();
assertEquals(numberOfThreads, counter.getCount());
}
@Test
public void testSummationWithConcurrencyAndWait() throws InterruptedException {
int numberOfThreads = 2;
ExecutorService service = Executors.newFixedThreadPool(10);
CountDownLatch latch = new CountDownLatch(numberOfThreads);
MyCounter counter = new MyCounter();
for (int i = 0; i < numberOfThreads; i++) {
service.submit(() -> {
try {
counter.incrementWithWait();
} catch (InterruptedException e) {
e.printStackTrace();
}
latch.countDown();
});
}
latch.await();
assertEquals(numberOfThreads, counter.getCount());
}
}

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