Merge pull request #76 from eugenp/master

update
This commit is contained in:
Maiklins 2020-12-29 18:15:32 +01:00 committed by GitHub
commit 391efe067c
1618 changed files with 12000 additions and 20308 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)

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)
- [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,13 +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)
- [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

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

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

@ -10,3 +10,4 @@ This module contains articles about Java 10 core features
- [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

@ -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)
- [Java 14 New Features](https://www.baeldung.com/java-14-new-features)

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,77 @@
<?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>${apache-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>
<apache-commons-lang3.version>3.11</apache-commons-lang3.version>
<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

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

@ -0,0 +1,6 @@
## Core Java Character
This module contains articles about Java Character Class
### Relevant Articles:
- Character#isAlphabetic vs Character#isLetter

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,37 @@
package com.baeldung.character;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
public class CharacterGeneralCategoryTypeUnitTest {
@Test
public void givenACharacter_whenUpperCaseLetter_thenAssertTrue() {
assertTrue(Character.getType('U') == Character.UPPERCASE_LETTER);
}
@Test
public void givenACharacter_whenLowerCaseLetter_thenAssertTrue() {
assertTrue(Character.getType('u') == Character.LOWERCASE_LETTER);
}
@Test
public void givenACharacter_whenTitleCaseLetter_thenAssertTrue() {
assertTrue(Character.getType('\u01f2') == Character.TITLECASE_LETTER);
}
@Test
public void givenACharacter_whenModifierLetter_thenAssertTrue() {
assertTrue(Character.getType('\u02b0') == Character.MODIFIER_LETTER);
}
@Test
public void givenACharacter_whenOtherLetter_thenAssertTrue() {
assertTrue(Character.getType('\u05d0') == Character.OTHER_LETTER);
}
@Test
public void givenACharacter_whenLetterNumber_thenAssertTrue() {
assertTrue(Character.getType('\u2164') == Character.LETTER_NUMBER);
}
}

View File

@ -0,0 +1,28 @@
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_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

@ -14,3 +14,4 @@
- [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

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

@ -6,4 +6,5 @@ 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)
- More articles: [[<-- prev]](/core-java-modules/core-java-collections-maps-2)

View File

@ -15,7 +15,11 @@
</parent>
<dependencies>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>${jmh-core.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,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

@ -13,7 +13,7 @@ This module contains articles about advanced topics about multithreading with co
- [Java Thread Deadlock and Livelock](https://www.baeldung.com/java-deadlock-livelock)
- [Guide to AtomicStampedReference in Java](https://www.baeldung.com/java-atomicstampedreference)
- [The ABA Problem in Concurrency](https://www.baeldung.com/cs/aba-concurrency)
- [Introduction to Lock-Free Data Structures](https://www.baeldung.com/lock-free-programming)
- [Introduction to Lock-Free Data Structures with Java Examples](https://www.baeldung.com/lock-free-programming)
- [Introduction to Exchanger in Java](https://www.baeldung.com/java-exchanger)
- [Why Not To Start A Thread In The Constructor?](https://www.baeldung.com/java-thread-constructor)
- [[<-- previous]](/core-java-modules/core-java-concurrency-advanced-2)

View File

@ -0,0 +1,263 @@
package com.baeldung.concurrent.stopexecution;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class StopExecution {
private static final Logger LOG = LoggerFactory.getLogger(StopExecution.class);
public static void main(String[] args) {
StopExecution stopExecution = new StopExecution();
//stopExecution.testUsingLoop();
//stopExecution.testTimer();
stopExecution.testScheduledExecutor();
LOG.info("done");
}
public void testUsingLoop() {
long start = System.currentTimeMillis();
long end = start + 5000;
List<String> items = new ArrayList<>();
int counter = 0;
// Let this loop run only upto 5 seconds
while (System.currentTimeMillis() < end && counter < items.size()) {
// Fetch the item from the list.
// Some expensive operation on the item.
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
counter++;
}
}
public static void testThreads() {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
LOG.info("inside run");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
LOG.info("exit run");
}
});
thread.start();
while (thread.getState() != Thread.State.TERMINATED) {
LOG.info(thread.getState().name());
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void testExecutor() {
final ExecutorService service = Executors.newSingleThreadExecutor();
Future<String> f = null;
try {
f = service.submit(() -> {
// Do you long running calculation here
try {
Thread.sleep(2737); // Simulate some delay
} catch (InterruptedException e) {
LOG.info("Interrupted");
return "interrupted";
}
LOG.info("Sleep finished");
return "42";
});
LOG.info(f.get(2, TimeUnit.SECONDS));
} catch (TimeoutException e) {
f.cancel(true);
LOG.error("Calculation took to long");
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
service.shutdown();
}
}
public void testExecutor2() {
final ExecutorService service = Executors.newSingleThreadExecutor();
Future f = null;
try {
f = service.submit(new LongRunningTask());
LOG.info("testExecutor2");
f.get(1, TimeUnit.SECONDS);
} catch (final TimeoutException e) {
f.cancel(true);
LOG.error("Calculation took to long");
} catch (final Exception e) {
throw new RuntimeException(e);
} finally {
service.shutdownNow();
}
}
public void testScheduledExecutor() {
LOG.info("testScheduledExecutor");
ScheduledExecutorService executor = Executors.newScheduledThreadPool(2);
Future future = executor.submit(new LongRunningTask());
executor.schedule(new Runnable() {
public void run() {
future.cancel(true);
}
}, 1000, TimeUnit.MILLISECONDS);
executor.shutdown();
}
public void testThreadAndInterrupt() {
Thread t;
try {
t = new Thread(new LongRunningTask());
LOG.info("testExecutor3");
long end = System.currentTimeMillis() + 2000;
t.start();
while (t.isAlive() && System.currentTimeMillis() < end) {
Thread.sleep(50);
}
t.interrupt();
} catch (final Exception e) {
throw new RuntimeException(e);
}
}
public void testTimer() {
LOG.info("Timer test");
Thread t = new Thread(new LongRunningTask());
Timer timeoutTimer = new Timer();
timeoutTimer.schedule(new TimeOutTask(t, timeoutTimer), 1000);
t.start();
}
class MyRunnableTask implements Runnable {
public void run() {
try {
LOG.info("MyRunnable...");
Thread.sleep(10000);
} catch (InterruptedException ie) {
LOG.info("MyRunnable interrupted...");
}
}
}
class TimeOutTask extends TimerTask {
private Thread t;
private Timer timer;
TimeOutTask(Thread t, Timer timer) {
this.t = t;
this.timer = timer;
}
public void run() {
if (t != null && t.isAlive()) {
t.interrupt();
timer.cancel();
}
}
}
class LongRunningTask implements Runnable {
@Override
public void run() {
longRunningSort();
}
private void longRunningOperation() {
LOG.info("long Running operation started");
try {
//Thread.sleep(500);
longFileRead();
LOG.info("long running operation finished");
} catch (InterruptedException e) {
LOG.info("long Running operation interrupted");
}
}
private void longRunningSort() {
LOG.info("long Running task started");
// Do you long running calculation here
int len = 100000;
List<Integer> numbers = new ArrayList<>();
try {
for (int i = len; i > 0; i--) {
//Thread.sleep(5)
numbers.add(i);
}
int i = 0;
for (i = 0; i < len; i++) {
int minIndex = i;
for (int j = i + 1; j < len; j++) {
if (numbers.get(minIndex) > numbers.get(j))
minIndex = j;
}
if (minIndex != i) {
int temp = numbers.get(i);
numbers.set(i, numbers.get(minIndex));
numbers.set(minIndex, temp);
}
throwExceptionOnThreadInterrupt();
}
LOG.info("Index position: " + i);
LOG.info("Long running task finished");
} catch (InterruptedException e) {
LOG.info("long Running operation interrupted");
}
}
private void longFileRead() throws InterruptedException {
String file = "input.txt";
ClassLoader classloader = getClass().getClassLoader();
try (InputStream inputStream = classloader.getResourceAsStream(file)) {
Reader inputStreamReader = new InputStreamReader(inputStream);
int data = inputStreamReader.read();
while (data != -1) {
char theChar = (char) data;
data = inputStreamReader.read();
throwExceptionOnThreadInterrupt();
}
} catch (IOException e) {
LOG.error("Exception: ", e);
}
}
private void throwExceptionOnThreadInterrupt() throws InterruptedException {
if (Thread.currentThread().interrupted()) {
throw new InterruptedException();
}
}
}
}

View File

@ -3,3 +3,8 @@
- [NoSuchMethodError in Java](https://www.baeldung.com/java-nosuchmethod-error)
- [IllegalArgumentException or NullPointerException for a Null Parameter?](https://www.baeldung.com/java-illegalargumentexception-or-nullpointerexception)
- [IllegalMonitorStateException in Java](https://www.baeldung.com/java-illegalmonitorstateexception)
- [AbstractMethodError in Java](https://www.baeldung.com/java-abstractmethoderror)
- [Java IndexOutOfBoundsException “Source Does Not Fit in Dest”](https://www.baeldung.com/java-indexoutofboundsexception)
- [Localizing Exception Messages in Java](https://www.baeldung.com/java-localize-exception-messages)
- [Explanation of ClassCastException in Java](https://www.baeldung.com/java-classcastexception)
- [NoSuchFieldError in Java](https://www.baeldung.com/java-nosuchfielderror)

View File

@ -17,6 +17,14 @@
</parent>
<dependencies>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.191</version>
<scope>test</scope>
</dependency>
<!-- test scoped -->
<dependency>
<groupId>org.assertj</groupId>

View File

@ -0,0 +1,14 @@
package com.baeldung.exception.indexoutofbounds;
import java.util.ArrayList;
import java.util.List;
public class CopyListUsingAddAllMethodDemo {
static List<Integer> copyList(List<Integer> source) {
List<Integer> destination = new ArrayList<>();
destination.addAll(source);
return destination;
}
}

View File

@ -0,0 +1,10 @@
package com.baeldung.exception.indexoutofbounds;
import java.util.Collections;
import java.util.List;
public class CopyListUsingCollectionsCopyMethodDemo {
static void copyList(List<Integer> source, List<Integer> destination) {
Collections.copy(destination, source);
}
}

View File

@ -0,0 +1,10 @@
package com.baeldung.exception.indexoutofbounds;
import java.util.ArrayList;
import java.util.List;
public class CopyListUsingConstructorDemo {
static List<Integer> copyList(List<Integer> source) {
return new ArrayList<>(source);
}
}

View File

@ -0,0 +1,12 @@
package com.baeldung.exception.indexoutofbounds;
import java.util.List;
import java.util.stream.Collectors;
public class CopyListUsingJava8StreamDemo {
static List<Integer> copyList(List<Integer> source) {
return source
.stream()
.collect(Collectors.toList());
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.exception.indexoutofbounds;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class IndexOutOfBoundsExceptionDemo {
static List<Integer> copyList(List<Integer> source) {
List<Integer> destination = new ArrayList<>(source.size());
Collections.copy(destination, source);
return destination;
}
}

View File

@ -1,9 +1,9 @@
package com.baeldung.exceptions.classcastexception;
public class Reptile implements Animal {
public class Amphibian implements Animal {
@Override
public String getName() {
return "Reptile";
return "Amphibian";
}
}

View File

@ -1,6 +1,6 @@
package com.baeldung.exceptions.classcastexception;
public class Frog extends Reptile {
public class Frog extends Amphibian {
@Override
public String getName() {

View File

@ -0,0 +1,47 @@
package com.baeldung.exceptions.localization;
import java.util.Locale;
public class LocalizedException extends Exception {
private static final long serialVersionUID = 1L;
private final String messageKey;
private final Locale locale;
public LocalizedException(String messageKey) {
this(messageKey, Locale.getDefault());
}
public LocalizedException(String messageKey, Locale locale) {
this.messageKey = messageKey;
this.locale = locale;
}
/**
* @return a localized message based on the messageKey provided at instantiation.
*/
public String getMessage() {
/*
* This is a deliberate role reversal of the default implementation of getLocalizedMessage.
* some logging frameworks like Log4J 1 & 2 and Logback will use getMessage instead of
* getLocalizedMessage when logging Throwables. If we want to use these frameworks in client
* applications to log localized messages, then we'll need to override getMessage in a
* similar fashion to return the appropriate content. Or, you can call getLocalizedMessage
* on your own to create the log content.
*/
return getLocalizedMessage();
}
/**
* @return a localized message based on the messageKey provided at instantiation.
*/
public String getLocalizedMessage() {
/*
* java.util.logging uses getLocalizedMessage when logging Throwables.
*/
return Messages.getMessageForLocale(messageKey, locale);
}
}

View File

@ -0,0 +1,27 @@
package com.baeldung.exceptions.localization;
import java.util.Locale;
import java.util.ResourceBundle;
public class Messages {
/**
* Retrieves the value for the messageKey from the locale-specific messages.properties, or from
* the base messages.properties for unsupported locales.
*
* @param messageKey The key for the message in the messages.properties ResourceBundle.
* @param locale The locale to search the message key.
* @return The value defined for the messageKey in the provided locale.
*/
public static String getMessageForLocale(String messageKey, Locale locale) {
/*
* For more complex implementations, you will want a var-args parameter for MessageFormat
* substitutions. Then we can read the value from the bundle and pass the value with the
* substitutions to MessageFormat to create the final message value.
*/
return ResourceBundle.getBundle("messages", locale)
.getString(messageKey);
}
}

View File

@ -0,0 +1,8 @@
package com.baeldung.exceptions.nosuchfielderror;
public class Dependency {
// This needed to be commented post compilation of NoSuchFielDError and Compile
public static String message = "Hello Baeldung!!";
}

View File

@ -0,0 +1,20 @@
package com.baeldung.exceptions.nosuchfielderror;
public class FieldErrorExample {
public static void main(String... args) {
fetchAndPrint();
}
public static String getDependentMessage() {
return Dependency.message;
}
public static void fetchAndPrint() {
System.out.println(getDependentMessage());
}
}

View File

@ -0,0 +1 @@
message.exception = I am an exception.

View File

@ -0,0 +1 @@
message.exception = Je suis une exception.

View File

@ -0,0 +1,18 @@
package com.baeldung.exception.indexoutofbounds;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
class CopyListUsingAddAllMethodDemoUnitTest {
@Test
void whenPassValidArrayList_thenCopyListUsingAddAllMethod() {
List<Integer> source = Arrays.asList(11, 22, 33);
assertEquals(source, CopyListUsingAddAllMethodDemo.copyList(source));
}
}

View File

@ -0,0 +1,31 @@
package com.baeldung.exception.indexoutofbounds;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
public class CopyListUsingCollectionsCopyMethodDemoUnitTest {
@Test
void whenCopyListUsingCollectionsCopy_thenOverrideAllDestinationListValues() {
List<Integer> source = Arrays.asList(11, 22, 33);
List<Integer> destination = Arrays.asList(1, 2, 3);
CopyListUsingCollectionsCopyMethodDemo.copyList(source, destination);
assertEquals(source, destination);
}
@Test
void whenCopyListUsingCollectionsCopy_thenOverrideInitialDestinationValuesAndOthersShouldBeUnchanged(){
List<Integer> source = Arrays.asList(11, 22, 33);
List<Integer> destination = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> expectedList = Arrays.asList(11, 22, 33, 4, 5);
CopyListUsingCollectionsCopyMethodDemo.copyList(source, destination);
assertEquals(expectedList, destination);
}
}

View File

@ -0,0 +1,18 @@
package com.baeldung.exception.indexoutofbounds;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
class CopyListUsingConstructorDemoUnitTest {
@Test
void whenCopyListUsingConstructor_thenMakeACopyOfList() {
List<Integer> source = Arrays.asList(11, 22, 33);
assertEquals(source, CopyListUsingConstructorDemo.copyList(source));
}
}

View File

@ -0,0 +1,18 @@
package com.baeldung.exception.indexoutofbounds;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
class CopyListUsingJava8StreamDemoUnitTest {
@Test
void whenCopyListUsingStream_thenMakeACopyOfArrayList() {
List<Integer> source = Arrays.asList(11, 22, 33);
assertEquals(source, CopyListUsingJava8StreamDemo.copyList(source));
}
}

View File

@ -0,0 +1,28 @@
package com.baeldung.exception.indexoutofbounds;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
class IndexOutOfBoundsExceptionDemoUnitTest {
@Test
void givenDestinationArrayListSizeIsZero_whenCopySourceArrayListToDestination_thenShouldThrowIndexOutOfBoundsException() {
List<Integer> source = Arrays.asList(1, 2, 3, 4, 5);
assertThrows(IndexOutOfBoundsException.class, () -> IndexOutOfBoundsExceptionDemo.copyList(source));
}
@Test
void givenSourceAndDestinationListSizeIsEqual_whenCopySourceArrayListToDestination_thenShouldNotThrowIndexOutOfBoundsException() {
List<Integer> source = Collections.emptyList();
assertEquals(source, IndexOutOfBoundsExceptionDemo.copyList(source));
}
}

View File

@ -0,0 +1,23 @@
package com.baeldung.exceptions.abstractmethoderror;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import static org.junit.jupiter.api.Assertions.assertNotNull;
class AbstractMethodErrorUnitTest {
private static final String url = "jdbc:h2:mem:A-DATABASE;INIT=CREATE SCHEMA IF NOT EXISTS myschema";
private static final String username = "sa";
@Test
void givenOldH2Database_whenCallgetSchemaMethod_thenThrowAbstractMethodError() throws SQLException {
Connection conn = DriverManager.getConnection(url, username, "");
assertNotNull(conn);
Assertions.assertThrows(AbstractMethodError.class, () -> conn.getSchema());
}
}

View File

@ -20,6 +20,8 @@ public class IllegalMonitorStateExceptionUnitTest {
senderThread.join(1000);
receiverThread.join(1000);
Thread.sleep(2000);
assertEquals("test", receiver.getMessage());
assertFalse(sender.hasIllegalMonitorStateExceptionOccurred());

View File

@ -0,0 +1,61 @@
package com.baeldung.exceptions.localization;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.Locale;
import static org.assertj.core.api.Assertions.assertThat;
public class LocalizedExceptionUnitTest {
private Locale originalDefaultLocale;
@Before
public void saveOriginalDefaultLocale() {
originalDefaultLocale = Locale.getDefault();
}
@After
public void restoreOriginalDefaultLocale() {
Locale.setDefault(originalDefaultLocale);
}
@Test
public void givenUsEnglishDefaultLocale_whenLocalizingMessage_thenMessageComesFromDefaultMessages() {
Locale.setDefault(Locale.US);
LocalizedException localizedException = new LocalizedException("message.exception");
String usEnglishLocalizedExceptionMessage = localizedException.getLocalizedMessage();
assertThat(usEnglishLocalizedExceptionMessage).isEqualTo("I am an exception.");
}
@Test
public void givenFranceFrenchDefaultLocale_whenLocalizingMessage_thenMessageComesFromFrenchTranslationMessages() {
Locale.setDefault(Locale.FRANCE);
LocalizedException localizedException = new LocalizedException("message.exception");
String franceFrenchLocalizedExceptionMessage = localizedException.getLocalizedMessage();
assertThat(franceFrenchLocalizedExceptionMessage).isEqualTo("Je suis une exception.");
}
@Test
public void givenUsEnglishProvidedLocale_whenLocalizingMessage_thenMessageComesFromDefaultMessage() {
LocalizedException localizedException = new LocalizedException("message.exception", Locale.US);
String usEnglishLocalizedExceptionMessage = localizedException.getLocalizedMessage();
assertThat(usEnglishLocalizedExceptionMessage).isEqualTo("I am an exception.");
}
@Test
public void givenFranceFrenchProvidedLocale_whenLocalizingMessage_thenMessageComesFromFrenchTranslationMessages() {
LocalizedException localizedException = new LocalizedException("message.exception", Locale.FRANCE);
String franceFrenchLocalizedExceptionMessage = localizedException.getLocalizedMessage();
assertThat(franceFrenchLocalizedExceptionMessage).isEqualTo("Je suis une exception.");
}
}

View File

@ -0,0 +1,25 @@
package com.baeldung.exceptions.localization;
import org.junit.Test;
import java.util.Locale;
import static org.assertj.core.api.Assertions.assertThat;
public class MessagesUnitTest {
@Test
public void givenUsEnglishLocale_whenRetrievingMessage_thenEnglishTranslationIsReturned() {
String translatedMessage = Messages.getMessageForLocale("message.exception", Locale.US);
assertThat(translatedMessage).isEqualTo("I am an exception.");
}
@Test
public void givenFranceFrenchLocale_whenRetrievingMessage_thenFrenchTranslationIsReturned() {
String translatedMessage = Messages.getMessageForLocale("message.exception", Locale.FRANCE);
assertThat(translatedMessage).isEqualTo("Je suis une exception.");
}
}

View File

@ -0,0 +1,16 @@
package com.baeldung.exceptions.nosuchfielderror;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class FieldErrorExampleUnitTest {
@Test
public void whenDependentMessage_returnMessage() {
String dependentMessage = FieldErrorExample.getDependentMessage();
assertTrue("Hello Baeldung!!".equals(dependentMessage));
}
}

View File

@ -0,0 +1,3 @@
## Relevant articles:
- [Functional Programming in Java](https://www.baeldung.com/java-functional-programming)

View File

@ -0,0 +1,18 @@
<?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-functional</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-functional</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>
</project>

View File

@ -0,0 +1,26 @@
package com.baeldung.functional;
import java.util.function.Function;
public class Currying {
private static Function<Double, Function<Double, Double>> weight = mass -> gravity -> mass * gravity;
private static Function<Double, Double> weightOnEarth = weight.apply(9.81);
private static Function<Double, Double> weightOnMars = weight.apply(3.75);
public static Double weightOnEarth(Double mass) {
return weightOnEarth.apply(mass);
}
public static Double weightOnMars(Double mass) {
return weightOnMars.apply(mass);
}
public static Function<Double, Double> weightOnEarth() {
final double gravity = 9.81;
return mass -> mass * gravity;
}
}

View File

@ -0,0 +1,24 @@
package com.baeldung.functional;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class FirstClassFunctions {
public static List<Integer> sortWithoutLambda(List<Integer> numbers) {
Collections.sort(numbers, new Comparator<Integer>() {
@Override
public int compare(Integer n1, Integer n2) {
return n1.compareTo(n2);
}
});
return numbers;
}
public static List<Integer> sortWithLambda(List<Integer> numbers) {
Collections.sort(numbers, (n1, n2) -> n1.compareTo(n2));
return numbers;
}
}

View File

@ -0,0 +1,20 @@
package com.baeldung.functional;
import java.util.function.Function;
public class FunctionComposition {
private static Function<Double, Double> log = (value) -> Math.log(value);
private static Function<Double, Double> sqrt = (value) -> Math.sqrt(value);
public static Double logThenSqrt(Double number) {
Function<Double, Double> logThenSqrt = sqrt.compose(log);
return (logThenSqrt.apply(3.14));
}
public static Double sqrtThenLog(Double number) {
Function<Double, Double> sqrtThenLog = sqrt.andThen(log);
return (sqrtThenLog.apply(3.14));
}
}

View File

@ -0,0 +1,36 @@
package com.baeldung.functional;
public class ImmutableData {
private final String someData;
private final AnotherImmutableData anotherImmutableData;
public ImmutableData(final String someData, final AnotherImmutableData anotherImmutableData) {
this.someData = someData;
this.anotherImmutableData = anotherImmutableData;
}
public String getSomeData() {
return someData;
}
public AnotherImmutableData getAnotherImmutableData() {
return anotherImmutableData;
}
public class AnotherImmutableData {
private final Integer someOtherData;
public AnotherImmutableData(final Integer someData) {
this.someOtherData = someData;
}
public Integer getSomeOtherData() {
return someOtherData;
}
}
}

View File

@ -0,0 +1,11 @@
package com.baeldung.functional;
import java.util.Optional;
public class Monads {
public static Optional<Integer> add(Optional<Integer> val1, Optional<Integer> val2) {
return val1.flatMap(first -> val2.flatMap(second -> Optional.of(first + second)));
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.functional;
import java.util.List;
import java.util.stream.Collectors;
public class PureFunctions {
public static Integer sum(List<Integer> numbers) {
return numbers.stream()
.collect(Collectors.summingInt(Integer::intValue));
}
}

View File

@ -0,0 +1,17 @@
package com.baeldung.functional;
public class Recursion {
public static Integer headRecursion(Integer number) {
return (number == 1) ? 1 : number * headRecursion(number - 1);
}
public static Integer tailRecursion(Integer number, Integer result) {
return (number == 1) ? result : tailRecursion(number - 1, result * number);
}
}

View File

@ -0,0 +1,39 @@
package com.baeldung.functional;
import java.util.logging.Level;
import java.util.logging.Logger;
public class ReferentialTransparency {
private static Logger logger = Logger.getGlobal();
public void main() {
String data = new SimpleData().setData("Baeldung")
.getData();
logger.log(Level.INFO, new SimpleData().setData("Baeldung")
.getData());
logger.log(Level.INFO, data);
logger.log(Level.INFO, "Baeldung");
}
public class SimpleData {
private Logger logger = Logger.getGlobal();
private String data;
public String getData() {
logger.log(Level.INFO, "Get data called for SimpleData");
return data;
}
public SimpleData setData(String data) {
logger.log(Level.INFO, "Set data called for SimpleData");
this.data = data;
return this;
}
}
}

View File

@ -0,0 +1,22 @@
package com.baeldung.functional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.Test;
public class CurryingUnitTest {
@Test
public void testWeightOnEarth() {
assertEquals(588.6, Currying.weightOnEarth(60.0), 0.1);
}
@Test
public void testWeightOnMars() {
assertEquals(225.0, Currying.weightOnMars(60.0), 0.1);
}
}

View File

@ -0,0 +1,27 @@
package com.baeldung.functional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Arrays;
import org.junit.Test;
public class FirstClassFunctionsUnitTest {
@Test
public void testSortingWithoutLambda() {
assertEquals(new Integer(8), FirstClassFunctions.sortWithoutLambda(Arrays.asList(new Integer(10), new Integer(8)))
.get(0));
}
@Test
public void testSortingWithLambda() {
assertEquals(new Integer(8), FirstClassFunctions.sortWithLambda(Arrays.asList(new Integer(10), new Integer(8)))
.get(0));
}
}

View File

@ -0,0 +1,23 @@
package com.baeldung.functional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.Test;
public class FunctionCompositionUnitTest {
@Test
public void testLogThenSqrt() {
assertEquals(1.07, FunctionComposition.logThenSqrt(3.14), 0.01);
}
@Test
public void testSqrtThenLog() {
assertEquals(0.57, FunctionComposition.sqrtThenLog(3.14), 0.01);
}
}

View File

@ -0,0 +1,19 @@
package com.baeldung.functional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Optional;
import org.junit.Test;
public class MonadsUnitTest {
@Test
public void testOptionalAdd() {
assertEquals(5, Monads.add(Optional.of(new Integer(2)), Optional.of(new Integer(3)))
.get());
}
}

View File

@ -0,0 +1,18 @@
package com.baeldung.functional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Arrays;
import org.junit.Test;
public class PureFunctionsUnitTets {
@Test
public void testSortingWithoutLambda() {
assertEquals(new Integer(18), PureFunctions.sum(Arrays.asList(new Integer(10), new Integer(8))));
}
}

View File

@ -0,0 +1,23 @@
package com.baeldung.functional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.Test;
public class RecursionUnitTest {
@Test
public void testHeadRecursion() {
assertEquals(120, Recursion.headRecursion(5));
}
@Test
public void testTailRecursion() {
assertEquals(120, Recursion.tailRecursion(5, 1));
}
}

View File

@ -12,4 +12,6 @@ This module contains articles about core Java input and output (IO)
- [Creating Temporary Directories in Java](https://www.baeldung.com/java-temp-directories)
- [Reading a Line at a Given Line Number From a File in Java](https://www.baeldung.com/java-read-line-at-number)
- [Find the Last Modified File in a Directory with Java](https://www.baeldung.com/java-last-modified-file)
- [Get a Filename Without the Extension in Java](https://www.baeldung.com/java-filename-without-extension)
- [Writing byte[] to a File in Java](https://www.baeldung.com/java-write-byte-array-file)
- [[<-- Prev]](/core-java-modules/core-java-io-2)

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