Merge remote-tracking branch 'upstream/master' into docker_compose_restart_policies

This commit is contained in:
Christian Jaimes
2022-05-22 07:51:45 -04:00
316 changed files with 5891 additions and 1509 deletions
+3 -4
View File
@@ -1,7 +1,7 @@
<?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">
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-poi-2</artifactId>
<version>0.0.1-SNAPSHOT</version>
@@ -25,5 +25,4 @@
<poi.version>5.2.0</poi.version>
</properties>
</project>
</project>
+1
View File
@@ -9,3 +9,4 @@ This module contains articles about Apache Spark
- [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)
- [Spark DataFrame](https://www.baeldung.com/spark-dataframes)
@@ -12,21 +12,29 @@ import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import scala.Tuple2;
public class ActionsUnitTest {
public static final Logger LOG = LoggerFactory.getLogger(ActionsUnitTest.class);
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[*]");
SparkConf conf = new SparkConf()
.setAppName("reduce")
.setMaster("local[*]")
.set("spark.driver.allowMultipleContexts", "true");
sc = new JavaSparkContext(conf);
tourists = sc.textFile("data/Tourist.csv").filter(line -> !line.startsWith("Region"));
}
@AfterClass
public static void cleanup() {
sc.close();
@@ -40,11 +48,11 @@ public class ActionsUnitTest {
})
.distinct();
Long numberOfCountries = countries.count();
System.out.println("Count: " + numberOfCountries);
LOG.debug("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"));
@@ -53,10 +61,12 @@ public class ActionsUnitTest {
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);
List<Tuple2<String, Double>> totalByCountry = expenditurePairRdd
.reduceByKey(Double::sum)
.collect();
LOG.debug("Total per Country: {}", totalByCountry);
for(Tuple2<String, Double> tuple : totalByCountry) {
if (tuple._1.equals("Mexico")) {
assertEquals(Double.valueOf(99164), tuple._2);
@@ -39,8 +39,10 @@ public class DataFrameUnitTest {
@Test
public void whenSelectSpecificColumns_thenColumnsFiltered() {
Dataset<Row> selectedData = data.select(col("country"), col("year"), col("value"));
selectedData.show();
// uncomment to see table
// selectedData.show();
List<String> resultList = Arrays.asList(selectedData.columns());
assertTrue(resultList.contains("country"));
assertTrue(resultList.contains("year"));
@@ -52,22 +54,26 @@ public class DataFrameUnitTest {
@Test
public void whenFilteringByCountry_thenCountryRecordsSelected() {
Dataset<Row> filteredData = data.filter(col("country").equalTo("Mexico"));
filteredData.show();
// uncomment to see table
// 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();
// uncomment to see table
// recordsPerCountry.show();
Dataset<Row> filteredData = recordsPerCountry.filter(col("country").equalTo("Sweden"));
assertEquals(new Long(12), filteredData.first()
assertEquals(12L, filteredData.first()
.get(1));
}
@@ -3,6 +3,7 @@ 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 static org.junit.Assert.assertTrue;
import org.apache.spark.api.java.function.FilterFunction;
import org.apache.spark.sql.DataFrameReader;
@@ -29,8 +30,8 @@ public class DatasetUnitTest {
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"),
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));
}
@@ -45,7 +46,9 @@ public class DatasetUnitTest {
Dataset<TouristData> selectedData = typedDataset
.filter((FilterFunction<TouristData>) record -> record.getCountry()
.equals("Norway"));
selectedData.show();
// uncomment to see output
// selectedData.show();
selectedData.foreach(record -> {
assertEquals("Norway", record.getCountry());
@@ -56,28 +59,41 @@ public class DatasetUnitTest {
public void whenGroupCountByCountry_thenContryTotalRecords() {
Dataset<Row> countriesCount = typedDataset.groupBy(typedDataset.col("country"))
.count();
countriesCount.show();
assertEquals(Long.valueOf(220), Long.valueOf(countriesCount.count()));
// uncomment to see output
// countriesCount.show();
assertEquals(220, 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();
Dataset<TouristData> filteredData = typedDataset.filter(
(FilterFunction<TouristData>) record -> record.getYear() != null
&& (Long.parseLong(record.getYear()) > 2010 && Long.parseLong(record.getYear()) < 2017));
// uncomment to see output
// filteredData.show();
assertEquals(394, filteredData.count());
filteredData.foreach(record -> {
assertTrue(Integer.parseInt(record.getYear()) > 2010 && Integer.parseInt(record.getYear()) < 2017);
});
}
@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();
Dataset<Row> filteredData = typedDataset.filter((FilterFunction<TouristData>) record -> record.getValue() != null
&& record.getSeries().contains("expenditure"))
.groupBy("country")
.agg(sum("value"));
// uncomment to see output
// filteredData.show();
assertEquals(212, filteredData.count());
}
}
@@ -23,8 +23,11 @@ public class TransformationsUnitTest {
@BeforeClass
public static void init() {
SparkConf conf = new SparkConf().setAppName("uppercaseCountries")
.setMaster("local[*]");
SparkConf conf = new SparkConf()
.setAppName("uppercaseCountries")
.setMaster("local[*]")
.set("spark.driver.allowMultipleContexts", "true");
sc = new JavaSparkContext(conf);
tourists = sc.textFile("data/Tourist.csv")
.filter(line -> !line.startsWith("Region")); //filter header row
+6 -1
View File
@@ -3,12 +3,17 @@
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>apache-tapestry</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>apache-tapestry</name>
<packaging>war</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<!-- To set up an application with a database, change the artifactId below to tapestry-hibernate,
and add a dependency on your JDBC driver. You'll also need to add Hibernate configuration files, such
@@ -8,6 +8,13 @@
<name>ShippingFunction</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>aws-lambda</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../../</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>com.amazonaws</groupId>
+20
View File
@@ -78,6 +78,25 @@
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>${maven-plugins-version}</version>
<executions>
<execution>
<id>copy</id>
<phase>compile</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<includeScope></includeScope>
<includeTypes>so,dll,dylib</includeTypes>
<outputDirectory>native-libs</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
@@ -99,6 +118,7 @@
<commons-codec-version>1.10.L001</commons-codec-version>
<jets3t-version>0.9.4.0006L</jets3t-version>
<maven-shade-plugin.version>3.0.0</maven-shade-plugin.version>
<maven-plugins-version>3.1.1</maven-plugins-version>
</properties>
</project>
+1 -2
View File
@@ -20,7 +20,6 @@
<artifactId>aws-java-sdk</artifactId>
<version>${aws-java-sdk.version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
@@ -58,7 +57,7 @@
</executions>
</plugin>
</plugins>
</build>
</build>
<properties>
<aws-java-sdk.version>1.11.290</aws-java-sdk.version>
+1 -1
View File
@@ -19,6 +19,6 @@
<module>aws-miscellaneous</module>
<module>aws-reactive</module>
<module>aws-s3</module>
</modules>
</modules>
</project>
@@ -12,3 +12,4 @@ This module contains articles about Java 11 core features
- [Java HTTPS Client Certificate Authentication](https://www.baeldung.com/java-https-client-certificate-authentication)
- [Call Methods at Runtime Using Java Reflection](https://www.baeldung.com/java-method-reflection)
- [Java HttpClient Basic Authentication](https://www.baeldung.com/java-httpclient-basic-auth)
- [Java HttpClient With SSL](https://www.baeldung.com/java-httpclient-ssl)
@@ -0,0 +1,32 @@
package com.baeldung.httpclient.ssl;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
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.util.Properties;
public class HttpClientSSLBypassUnitTest {
@Test
public void whenHttpsRequest_thenCorrect() throws IOException, InterruptedException {
final Properties props = System.getProperties();
props.setProperty("jdk.internal.httpclient.disableHostnameVerification", Boolean.TRUE.toString());
HttpClient httpClient = HttpClient.newBuilder()
.build();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://www.testingmcafeesites.com/"))
.build();
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
props.setProperty("jdk.internal.httpclient.disableHostnameVerification", Boolean.FALSE.toString());
Assertions.assertEquals(200, response.statusCode());
}
}
@@ -0,0 +1,41 @@
package com.baeldung.httpclient.ssl;
import org.junit.Test;
import javax.net.ssl.SSLHandshakeException;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import static org.junit.Assert.assertEquals;
public class HttpClientSSLUnitTest {
@Test
public void whenValidHttpsRequest_thenCorrect() throws URISyntaxException, IOException, InterruptedException {
HttpClient httpClient = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("https://www.google.com/"))
.build();
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
assertEquals(200, response.statusCode());
}
@Test(expected = SSLHandshakeException.class)
public void whenInvalidHttpsRequest_thenInCorrect() throws IOException, InterruptedException {
HttpClient httpClient = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://expired.badssl.com/"))
.build();
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
assertEquals(200, response.statusCode());
}
}
@@ -0,0 +1,36 @@
package com.baeldung.java9.delimiters;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.regex.Pattern;
public class DelimiterDemo {
public static List<String> scannerWithDelimiter(String input, String delimiter) {
try (Scanner scan = new Scanner(input)) {
scan.useDelimiter(delimiter);
List<String> result = new ArrayList<String>();
scan.forEachRemaining(result::add);
return result;
}
}
public static List<String> scannerWithDelimiterUsingPattern(String input, Pattern delimiter) {
try (Scanner scan = new Scanner(input)) {
scan.useDelimiter(delimiter);
List<String> result = new ArrayList<String>();
scan.forEachRemaining(result::add);
return result;
}
}
public static List<String> baseScanner(String input) {
try (Scanner scan = new Scanner(input)) {
List<String> result = new ArrayList<String>();
scan.forEachRemaining(result::add);
return result;
}
}
}
@@ -0,0 +1,67 @@
package com.baeldung.java9.delimiters;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Arrays;
import java.util.List;
import java.util.function.BiFunction;
import java.util.regex.Pattern;
import org.junit.jupiter.api.Test;
class DelimiterDemoUnitTest {
@Test
void givenSimpleCharacterDelimiter_whenScannerWithDelimiter_ThenInputIsCorrectlyParsed() {
checkOutput(DelimiterDemo::scannerWithDelimiter, "Welcome to Baeldung", "\\s", Arrays.asList("Welcome", "to", "Baeldung"));
}
@Test
void givenStringDelimiter_whenScannerWithDelimiter_ThenInputIsCorrectlyParsed() {
checkOutput(DelimiterDemo::scannerWithDelimiter, "HelloBaeldungHelloWorld", "Hello", Arrays.asList("Baeldung", "World"));
}
@Test
void givenVariousPossibleDelimiters_whenScannerWithDelimiter_ThenInputIsCorrectlyParsed() {
checkOutput(DelimiterDemo::scannerWithDelimiter, "Welcome to Baeldung.\nThank you for reading.\nThe team", "\n|\\s", Arrays.asList("Welcome", "to", "Baeldung.", "Thank", "you", "for", "reading.", "The", "team"));
}
@Test
void givenWildcardRegexDelimiter_whenScannerWithDelimiter_ThenInputIsCorrectlyParsed() {
checkOutput(DelimiterDemo::scannerWithDelimiter, "1aaaaaaa2aa3aaa4", "a+", Arrays.asList("1", "2", "3", "4"));
}
@Test
void givenSimpleCharacterDelimiter_whenScannerWithDelimiterUsingPattern_ThenInputIsCorrectlyParsed() {
checkOutput(DelimiterDemo::scannerWithDelimiterUsingPattern, "Welcome to Baeldung", Pattern.compile("\\s"), Arrays.asList("Welcome", "to", "Baeldung"));
}
@Test
void givenStringDelimiter_whenScannerWithDelimiterUsingPattern_ThenInputIsCorrectlyParsed() {
checkOutput(DelimiterDemo::scannerWithDelimiterUsingPattern, "HelloBaeldungHelloWorld", Pattern.compile("Hello"), Arrays.asList("Baeldung", "World"));
}
@Test
void givenVariousPossibleDelimiters_whenScannerWithDelimiterUsingPattern_ThenInputIsCorrectlyParsed() {
checkOutput(DelimiterDemo::scannerWithDelimiterUsingPattern, "Welcome to Baeldung.\nThank you for reading.\nThe team", Pattern.compile("\n|\\s"), Arrays.asList("Welcome", "to", "Baeldung.", "Thank", "you", "for", "reading.", "The", "team"));
}
@Test
void givenWildcardRegexDelimiters_whenScannerWithDelimiterUsingPattern_ThenInputIsCorrectlyParsed() {
checkOutput(DelimiterDemo::scannerWithDelimiterUsingPattern, "1aaaaaaa2aa3aaa4", Pattern.compile("a*"), Arrays.asList("1", "2", "3", "4"));
}
void checkOutput(BiFunction<String, String, List<String>> function, String input, String delimiter, List<String> expectedOutput) {
assertEquals(expectedOutput, function.apply(input, delimiter));
}
void checkOutput(BiFunction<String, Pattern, List<String>> function, String input, Pattern delimiter, List<String> expectedOutput) {
assertEquals(expectedOutput, function.apply(input, delimiter));
}
@Test
void whenBaseScanner_ThenWhitespacesAreUsedAsDelimiters() {
assertEquals(List.of("Welcome", "at", "Baeldung"), DelimiterDemo.baseScanner("Welcome at Baeldung"));
}
}
@@ -12,3 +12,4 @@
- [Sorting in Java](https://www.baeldung.com/java-sorting)
- [Getting the Size of an Iterable in Java](https://www.baeldung.com/java-iterable-size)
- [Java Null-Safe Streams from Collections](https://www.baeldung.com/java-null-safe-streams-from-collections)
- [Differences Between Iterator and Iterable and How to Use Them?](https://www.baeldung.com/java-iterator-vs-iterable)
@@ -0,0 +1,17 @@
package com.baeldung.collections.iterable;
class CustomIterableClient {
public static void main(String[] args) {
ShoppingCart<Product> shoppingCart = new ShoppingCart<>();
shoppingCart.add(new Product("Tuna", 42));
shoppingCart.add(new Product("Eggplant", 65));
shoppingCart.add(new Product("Salad", 45));
shoppingCart.add(new Product("Banana", 29));
for (Product product : shoppingCart) {
System.out.println(product.getName());
}
}
}
@@ -0,0 +1,32 @@
package com.baeldung.collections.iterable;
import java.util.Iterator;
import java.util.List;
public class IterableExample {
public void iterateUsingIterator(List<Integer> numbers) {
Iterator<Integer> iterator = numbers.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
public void iterateUsingEnhancedForLoop(List<Integer> numbers) {
for (Integer number : numbers) {
System.out.println(number);
}
}
public void iterateUsingForEachLoop(List<Integer> numbers) {
numbers.forEach(System.out::println);
}
public void removeElementsUsingIterator(List<Integer> numbers) {
Iterator<Integer> iterator = numbers.iterator();
while (iterator.hasNext()) {
iterator.next();
iterator.remove();
}
}
}
@@ -0,0 +1,28 @@
package com.baeldung.collections.iterable;
class Product {
private String name;
private double price;
public Product(String code, double price) {
this.name = code;
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
@@ -0,0 +1,72 @@
package com.baeldung.collections.iterable;
import java.util.Arrays;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class ShoppingCart<E> implements Iterable<E> {
private E[] elementData;
private int size;
public ShoppingCart() {
this.elementData = (E[]) new Object[]{};
}
public void add(E element) {
ensureCapacity(size + 1);
elementData[size++] = element;
}
private void ensureCapacity(int minCapacity) {
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1);
if (newCapacity - minCapacity < 0) {
newCapacity = minCapacity;
}
elementData = Arrays.copyOf(elementData, newCapacity);
}
@Override
public Iterator<E> iterator() {
return new ShoppingCartIterator();
}
public class ShoppingCartIterator implements Iterator<E> {
int cursor;
int lastReturned = -1;
public boolean hasNext() {
return cursor != size;
}
public E next() {
return getNextElement();
}
private E getNextElement() {
int current = cursor;
exist(current);
E[] elements = ShoppingCart.this.elementData;
validate(elements, current);
cursor = current + 1;
lastReturned = current;
return elements[lastReturned];
}
private void exist(int current) {
if (current >= size) {
throw new NoSuchElementException();
}
}
private void validate(E[] elements, int current) {
if (current >= elements.length) {
throw new ConcurrentModificationException();
}
}
}
}
@@ -0,0 +1,14 @@
package com.baeldung.collections.iterator;
import java.util.Iterator;
class CustomIteratorClient {
public static void main(String[] args) {
Iterator<Integer> iterator = Numbers.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}
@@ -0,0 +1,60 @@
package com.baeldung.collections.iterator;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
class Numbers {
private static final List<Integer> NUMBER_LIST = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
private Numbers() {
}
public static Iterator<Integer> iterator() {
return new PrimeIterator();
}
private static class PrimeIterator implements Iterator<Integer> {
private int cursor;
@Override
public Integer next() {
exist(cursor);
return NUMBER_LIST.get(cursor++);
}
private void exist(int current) {
if (current >= NUMBER_LIST.size()) {
throw new NoSuchElementException();
}
}
@Override
public boolean hasNext() {
if (cursor > NUMBER_LIST.size()) {
return false;
}
for (int i = cursor; i < NUMBER_LIST.size(); i++) {
if (isPrime(NUMBER_LIST.get(i))) {
cursor = i;
return true;
}
}
return false;
}
private boolean isPrime(int number) {
for (int i = 2; i <= number / 2; ++i) {
if (number % i == 0) {
return false;
}
}
return true;
}
}
}
@@ -0,0 +1,54 @@
package com.baeldung.collections.iterable;
import com.baeldung.collections.iterable.IterableExample;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
class IterableUnitTest {
private static List<Integer> getNumbers() {
List<Integer> numbers = new ArrayList<>();
numbers.add(10);
numbers.add(20);
numbers.add(30);
numbers.add(40);
return numbers;
}
@Test
void givenNumbers_whenUsingIterator_thenCorrectSize() {
List<Integer> numbers = getNumbers();
IterableExample iterableExample = new IterableExample();
iterableExample.iterateUsingIterator(numbers);
assertEquals(4, numbers.size());
}
@Test
void givenNumbers_whenRemoveElements_thenEmptyList() {
List<Integer> numbers = getNumbers();
IterableExample iterableExample = new IterableExample();
iterableExample.removeElementsUsingIterator(numbers);
assertEquals(0, numbers.size());
}
@Test
void givenNumbers_whenIterateUsingEnhancedForLoop_thenCorrectSize() {
List<Integer> numbers = getNumbers();
IterableExample iterableExample = new IterableExample();
iterableExample.iterateUsingEnhancedForLoop(numbers);
assertEquals(4, numbers.size());
}
@Test
void givenNumbers_whenIterateUsingForEachLoop_thenCorrectSize() {
List<Integer> numbers = getNumbers();
IterableExample iterableExample = new IterableExample();
iterableExample.iterateUsingForEachLoop(numbers);
assertEquals(4, numbers.size());
}
}
@@ -14,4 +14,16 @@
<version>0.0.1-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>${commons-lang.version}</version>
</dependency>
</dependencies>
<properties>
<commons-lang.version>2.2</commons-lang.version>
</properties>
</project>
@@ -0,0 +1,72 @@
package com.baeldung.collections.sorting;
import java.util.Date;
public class Employee implements Comparable<Employee>{
private String name;
private int age;
private double salary;
private Date joiningDate;
public Employee(String name, int age, double salary, Date joiningDate) {
this.name = name;
this.age = age;
this.salary = salary;
this.joiningDate = joiningDate;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public Date getJoiningDate() {
return joiningDate;
}
public void setJoiningDate(Date joiningDate) {
this.joiningDate = joiningDate;
}
@Override
public boolean equals(Object obj) {
return ((Employee) obj).getName()
.equals(getName());
}
@Override
public String toString() {
return new StringBuffer().append("(")
.append(getName()).append(",")
.append(getAge())
.append(",")
.append(getSalary()).append(",").append(getJoiningDate())
.append(")")
.toString();
}
@Override
public int compareTo(Employee employee) {
return getJoiningDate().compareTo(employee.getJoiningDate());
}
}
@@ -0,0 +1,146 @@
package com.baeldung.collections.sorting;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import org.apache.commons.lang.time.DateUtils;
import org.junit.Before;
import org.junit.Test;
public class EmployeeSortingByDateUnitTest {
private List<Employee> employees = new ArrayList<>();
private List<Employee> employeesSortedByDateAsc = new ArrayList<>();
private List<Employee> employeesSortedByDateDesc = new ArrayList<>();
@Before
public void initVariables() {
Collections.addAll(employees,
new Employee("Earl", 43, 10000, DateUtils.addMonths(new Date(), -2)),
new Employee("Frank", 33, 7000, DateUtils.addDays(new Date(), -20)),
new Employee("Steve", 26, 6000, DateUtils.addDays(new Date(), -10)),
new Employee("Jessica", 23, 4000, DateUtils.addMonths(new Date(), -6)),
new Employee("Pearl", 33, 6000, DateUtils.addYears(new Date(), -1)),
new Employee("John", 23, 5000, new Date())
);
Collections.addAll(employeesSortedByDateDesc,
new Employee("John", 23, 5000, new Date()),
new Employee("Steve", 26, 6000, DateUtils.addDays(new Date(), -10)),
new Employee("Frank", 33, 7000, DateUtils.addDays(new Date(), -20)),
new Employee("Earl", 43, 10000, DateUtils.addMonths(new Date(), -2)),
new Employee("Jessica", 23, 4000, DateUtils.addMonths(new Date(), -6)),
new Employee("Pearl", 33, 6000, DateUtils.addYears(new Date(), -1))
);
Collections.addAll(employeesSortedByDateAsc,
new Employee("Pearl", 33, 6000, DateUtils.addYears(new Date(), -1)),
new Employee("Jessica", 23, 4000, DateUtils.addMonths(new Date(), -6)),
new Employee("Earl", 43, 10000, DateUtils.addMonths(new Date(), -2)),
new Employee("Frank", 33, 7000, DateUtils.addDays(new Date(), -20)),
new Employee("Steve", 26, 6000, DateUtils.addDays(new Date(), -10)),
new Employee("John", 23, 5000, new Date())
);
}
@Test
public void givenEmpList_SortEmpList_thenSortedListinNaturalOrder() {
Collections.sort(employees);
assertEquals(employees, employeesSortedByDateAsc);
}
@Test
public void givenEmpList_SortEmpList_thenCheckSortedList() {
Collections.sort(employees, new Comparator<Employee>() {
public int compare(Employee o1, Employee o2) {
return o1.getJoiningDate().compareTo(o2.getJoiningDate());
}
});
assertEquals(employees, employeesSortedByDateAsc);
}
@Test
public void givenEmpList_SortEmpList_thenCheckSortedListV1() {
Collections.sort(employees, new Comparator<Employee>() {
public int compare(Employee emp1, Employee emp2) {
if (emp1.getJoiningDate() == null || emp2.getJoiningDate() == null)
return 0;
return emp1.getJoiningDate().compareTo(emp2.getJoiningDate());
}
});
assertEquals(employees, employeesSortedByDateAsc);
}
@Test
public void givenEmpList_SortEmpList_thenSortedListinAscOrder() {
Collections.sort(employees, Collections.reverseOrder());
assertEquals(employees, employeesSortedByDateDesc);
}
@Test
public void givenEmpList_SortEmpList_thenCheckSortedListAsc() {
Collections.sort(employees, new Comparator<Employee>() {
public int compare(Employee emp1, Employee emp2) {
return emp2.getJoiningDate().compareTo(emp1.getJoiningDate());
}
});
assertEquals(employees, employeesSortedByDateDesc);
}
@Test
public void givenEmpList_SortEmpList_thenCheckSortedListAscV1() {
Collections.sort(employees, new Comparator<Employee>() {
public int compare(Employee emp1, Employee emp2) {
if (emp1.getJoiningDate() == null || emp2.getJoiningDate() == null)
return 0;
return emp2.getJoiningDate().compareTo(emp1.getJoiningDate());
}
});
assertEquals(employees, employeesSortedByDateDesc);
}
@Test
public void givenEmpList_SortEmpList_thenCheckSortedListDescLambda() {
Collections.sort(employees,
(emp1, emp2) -> emp2.getJoiningDate().compareTo(emp1.getJoiningDate()));
assertEquals(employees, employeesSortedByDateDesc);
}
@Test
public void givenEmpList_SortEmpList_thenCheckSortedListDescLambdaV1() {
Collections.sort(employees, (emp1, emp2) -> {
if (emp1.getJoiningDate() == null || emp2.getJoiningDate() == null)
return 0;
return emp2.getJoiningDate().compareTo(emp1.getJoiningDate());
});
assertEquals(employees, employeesSortedByDateDesc);
}
@Test
public void givenEmpList_SortEmpList_thenCheckSortedListAscLambda() {
Collections.sort(employees,
Comparator.comparing(Employee::getJoiningDate));
assertEquals(employees, employeesSortedByDateAsc);
}
}
@@ -0,0 +1,7 @@
## Core Java Collections List (Part 4)
This module contains articles about the Java List collection
### Relevant Articles:
- [Working With a List of Lists in Java](https://www.baeldung.com/java-list-of-lists)
- [[<-- Prev]](/core-java-modules/core-java-collections-list-3)
@@ -0,0 +1,56 @@
<?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-list-4</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-collections-list-4</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>${commons-collections4.version}</version>
</dependency>
<dependency>
<groupId>net.sf.trove4j</groupId>
<artifactId>trove4j</artifactId>
<version>${trove4j.version}</version>
</dependency>
<dependency>
<groupId>it.unimi.dsi</groupId>
<artifactId>fastutil</artifactId>
<version>${fastutil.version}</version>
</dependency>
<dependency>
<groupId>colt</groupId>
<artifactId>colt</artifactId>
<version>${colt.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>${jmh-core.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>${jmh-generator.version}</version>
</dependency>
</dependencies>
<properties>
<trove4j.version>3.0.2</trove4j.version>
<fastutil.version>8.1.0</fastutil.version>
<colt.version>1.2.0</colt.version>
</properties>
</project>

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