Merge remote-tracking branch 'baeldung/master' into BAEL-4015
This commit is contained in:
commit
86137d30db
@ -6,10 +6,12 @@ import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent;
|
|||||||
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent;
|
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent;
|
||||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import com.zaxxer.hikari.HikariDataSource;
|
||||||
import org.hibernate.SessionFactory;
|
import org.hibernate.SessionFactory;
|
||||||
import org.hibernate.boot.MetadataSources;
|
import org.hibernate.boot.MetadataSources;
|
||||||
import org.hibernate.boot.registry.StandardServiceRegistry;
|
import org.hibernate.boot.registry.StandardServiceRegistry;
|
||||||
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
|
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
|
||||||
|
import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
|
||||||
|
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
@ -22,11 +24,14 @@ import static org.hibernate.cfg.AvailableSettings.PASS;
|
|||||||
*/
|
*/
|
||||||
public class App implements RequestHandler<APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent> {
|
public class App implements RequestHandler<APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent> {
|
||||||
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
|
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
|
||||||
|
private SessionFactory sessionFactory = createSessionFactory();
|
||||||
|
|
||||||
public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent input, Context context) {
|
public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent input, Context context) {
|
||||||
try (SessionFactory sessionFactory = createSessionFactory()) {
|
try {
|
||||||
ShippingService service = new ShippingService(sessionFactory, new ShippingDao());
|
ShippingService service = new ShippingService(sessionFactory, new ShippingDao());
|
||||||
return routeRequest(input, service);
|
return routeRequest(input, service);
|
||||||
|
} finally {
|
||||||
|
flushConnectionPool();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -105,4 +110,12 @@ private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
|
|||||||
.buildMetadata()
|
.buildMetadata()
|
||||||
.buildSessionFactory();
|
.buildSessionFactory();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void flushConnectionPool() {
|
||||||
|
ConnectionProvider connectionProvider = sessionFactory.getSessionFactoryOptions()
|
||||||
|
.getServiceRegistry()
|
||||||
|
.getService(ConnectionProvider.class);
|
||||||
|
HikariDataSource hikariDataSource = connectionProvider.unwrap(HikariDataSource.class);
|
||||||
|
hikariDataSource.getHikariPoolMXBean().softEvictConnections();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -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));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -4,4 +4,4 @@ This module contains articles about Java 15.
|
|||||||
|
|
||||||
### Relevant articles
|
### Relevant articles
|
||||||
|
|
||||||
- TODO: add article links here
|
- [Sealed Classes and Interfaces in Java 15](https://www.baeldung.com/java-sealed-classes-interfaces)
|
||||||
|
@ -51,8 +51,8 @@
|
|||||||
<configuration>
|
<configuration>
|
||||||
<release>${maven.compiler.release}</release>
|
<release>${maven.compiler.release}</release>
|
||||||
<compilerArgs>--enable-preview</compilerArgs>
|
<compilerArgs>--enable-preview</compilerArgs>
|
||||||
<source>15</source>
|
<source>14</source>
|
||||||
<target>15</target>
|
<target>14</target>
|
||||||
</configuration>
|
</configuration>
|
||||||
</plugin>
|
</plugin>
|
||||||
<plugin>
|
<plugin>
|
||||||
|
@ -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");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -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();
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,4 @@
|
|||||||
|
package com.baeldung.whatsnew.sealedclasses;
|
||||||
|
|
||||||
|
public final class Manager extends Person {
|
||||||
|
}
|
@ -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();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -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)
|
- [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)
|
- [What is \[Ljava.lang.Object;?](https://www.baeldung.com/java-tostring-array)
|
||||||
- [Guide to ArrayStoreException](https://www.baeldung.com/java-arraystoreexception)
|
- [Guide to ArrayStoreException](https://www.baeldung.com/java-arraystoreexception)
|
||||||
|
- [Creating a Generic Array in Java](https://www.baeldung.com/java-generic-array)
|
||||||
|
@ -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;
|
||||||
|
}
|
||||||
|
}
|
@ -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]);
|
||||||
|
}
|
||||||
|
}
|
@ -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);
|
||||||
|
}
|
||||||
|
}
|
6
core-java-modules/core-java-char/README.md
Normal file
6
core-java-modules/core-java-char/README.md
Normal file
@ -0,0 +1,6 @@
|
|||||||
|
## Core Java Character
|
||||||
|
|
||||||
|
This module contains articles about Java Character Class
|
||||||
|
|
||||||
|
### Relevant Articles:
|
||||||
|
- Character#isAlphabetic vs Character#isLetter
|
42
core-java-modules/core-java-char/pom.xml
Normal file
42
core-java-modules/core-java-char/pom.xml
Normal 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>
|
@ -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);
|
||||||
|
}
|
||||||
|
}
|
@ -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'));
|
||||||
|
}
|
||||||
|
}
|
@ -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)
|
- [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)
|
- [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)
|
- [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)
|
||||||
|
@ -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]; });
|
||||||
|
}
|
||||||
|
}
|
@ -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());
|
||||||
|
}
|
||||||
|
}
|
@ -6,3 +6,4 @@
|
|||||||
- [AbstractMethodError in Java](https://www.baeldung.com/java-abstractmethoderror)
|
- [AbstractMethodError in Java](https://www.baeldung.com/java-abstractmethoderror)
|
||||||
- [Java IndexOutOfBoundsException “Source Does Not Fit in Dest”](https://www.baeldung.com/java-indexoutofboundsexception)
|
- [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)
|
- [Localizing Exception Messages in Java](https://www.baeldung.com/java-localize-exception-messages)
|
||||||
|
- [Explanation of ClassCastException in Java](https://www.baeldung.com/java-classcastexception)
|
||||||
|
@ -1,9 +1,9 @@
|
|||||||
package com.baeldung.exceptions.classcastexception;
|
package com.baeldung.exceptions.classcastexception;
|
||||||
|
|
||||||
public class Reptile implements Animal {
|
public class Amphibian implements Animal {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String getName() {
|
public String getName() {
|
||||||
return "Reptile";
|
return "Amphibian";
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -1,6 +1,6 @@
|
|||||||
package com.baeldung.exceptions.classcastexception;
|
package com.baeldung.exceptions.classcastexception;
|
||||||
|
|
||||||
public class Frog extends Reptile {
|
public class Frog extends Amphibian {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String getName() {
|
public String getName() {
|
||||||
|
@ -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!!";
|
||||||
|
|
||||||
|
}
|
@ -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());
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -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));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -16,31 +16,42 @@ public class UnzipFile {
|
|||||||
ZipEntry zipEntry = zis.getNextEntry();
|
ZipEntry zipEntry = zis.getNextEntry();
|
||||||
while (zipEntry != null) {
|
while (zipEntry != null) {
|
||||||
final File newFile = newFile(destDir, zipEntry);
|
final File newFile = newFile(destDir, zipEntry);
|
||||||
final FileOutputStream fos = new FileOutputStream(newFile);
|
if (zipEntry.isDirectory()) {
|
||||||
int len;
|
if (!newFile.isDirectory() && !newFile.mkdirs()) {
|
||||||
while ((len = zis.read(buffer)) > 0) {
|
throw new IOException("Failed to create directory " + newFile);
|
||||||
fos.write(buffer, 0, len);
|
}
|
||||||
|
} else {
|
||||||
|
File parent = newFile.getParentFile();
|
||||||
|
if (!parent.isDirectory() && !parent.mkdirs()) {
|
||||||
|
throw new IOException("Failed to create directory " + parent);
|
||||||
|
}
|
||||||
|
|
||||||
|
final FileOutputStream fos = new FileOutputStream(newFile);
|
||||||
|
int len;
|
||||||
|
while ((len = zis.read(buffer)) > 0) {
|
||||||
|
fos.write(buffer, 0, len);
|
||||||
|
}
|
||||||
|
fos.close();
|
||||||
}
|
}
|
||||||
fos.close();
|
|
||||||
zipEntry = zis.getNextEntry();
|
zipEntry = zis.getNextEntry();
|
||||||
}
|
}
|
||||||
zis.closeEntry();
|
zis.closeEntry();
|
||||||
zis.close();
|
zis.close();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @see https://snyk.io/research/zip-slip-vulnerability
|
* @see https://snyk.io/research/zip-slip-vulnerability
|
||||||
*/
|
*/
|
||||||
public static File newFile(File destinationDir, ZipEntry zipEntry) throws IOException {
|
public static File newFile(File destinationDir, ZipEntry zipEntry) throws IOException {
|
||||||
File destFile = new File(destinationDir, zipEntry.getName());
|
File destFile = new File(destinationDir, zipEntry.getName());
|
||||||
|
|
||||||
String destDirPath = destinationDir.getCanonicalPath();
|
String destDirPath = destinationDir.getCanonicalPath();
|
||||||
String destFilePath = destFile.getCanonicalPath();
|
String destFilePath = destFile.getCanonicalPath();
|
||||||
|
|
||||||
if (!destFilePath.startsWith(destDirPath + File.separator)) {
|
if (!destFilePath.startsWith(destDirPath + File.separator)) {
|
||||||
throw new IOException("Entry is outside of the target dir: " + zipEntry.getName());
|
throw new IOException("Entry is outside of the target dir: " + zipEntry.getName());
|
||||||
}
|
}
|
||||||
|
|
||||||
return destFile;
|
return destFile;
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -0,0 +1,68 @@
|
|||||||
|
package com.baeldung.iterationcounter;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.concurrent.atomic.AtomicInteger;
|
||||||
|
import java.util.function.BiConsumer;
|
||||||
|
import java.util.function.Consumer;
|
||||||
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
|
public class IterationCounter {
|
||||||
|
public static final List<String> IMDB_TOP_MOVIES = Arrays.asList("The Shawshank Redemption",
|
||||||
|
"The Godfather", "The Godfather II", "The Dark Knight");
|
||||||
|
|
||||||
|
public static List<String> getRankingsWithForLoop(List<String> movies) {
|
||||||
|
List<String> rankings = new ArrayList<>();
|
||||||
|
for (int i = 0; i < movies.size(); i++) {
|
||||||
|
String ranking = (i + 1) + ": " + movies.get(i);
|
||||||
|
rankings.add(ranking);
|
||||||
|
}
|
||||||
|
return rankings;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static List<String> getRankingsWithForEachLoop(List<String> movies) {
|
||||||
|
List<String> rankings = new ArrayList<>();
|
||||||
|
int i = 0;
|
||||||
|
for (String movie : movies) {
|
||||||
|
String ranking = (i + 1) + ": " + movies.get(i);
|
||||||
|
rankings.add(ranking);
|
||||||
|
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
return rankings;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static List<String> getRankingsWithFunctionalForEachLoop(List<String> movies) {
|
||||||
|
List<String> rankings = new ArrayList<>();
|
||||||
|
forEachWithCounter(movies, (i, movie) -> {
|
||||||
|
String ranking = (i + 1) + ": " + movie;
|
||||||
|
rankings.add(ranking);
|
||||||
|
});
|
||||||
|
|
||||||
|
return rankings;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static <T> void forEachWithCounter(Iterable<T> source, BiConsumer<Integer, T> consumer) {
|
||||||
|
int i = 0;
|
||||||
|
for (T item : source) {
|
||||||
|
consumer.accept(i, item);
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static List<String> getRankingsWithStream(Stream<String> movies) {
|
||||||
|
List<String> rankings = new ArrayList<>();
|
||||||
|
movies.forEach(withCounter((i, movie) -> {
|
||||||
|
String ranking = (i + 1) + ": " + movie;
|
||||||
|
rankings.add(ranking);
|
||||||
|
}));
|
||||||
|
|
||||||
|
return rankings;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static <T> Consumer<T> withCounter(BiConsumer<Integer, T> consumer) {
|
||||||
|
AtomicInteger counter = new AtomicInteger(0);
|
||||||
|
return item -> consumer.accept(counter.getAndIncrement(), item);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,36 @@
|
|||||||
|
package com.baeldung.iterationcounter;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import static com.baeldung.iterationcounter.IterationCounter.*;
|
||||||
|
import static org.assertj.core.api.Assertions.*;
|
||||||
|
|
||||||
|
public class IterationCounterUnitTest {
|
||||||
|
@Test
|
||||||
|
public void givenRankings_whenCalculateWithForLoop_thenRankingsCorrect() {
|
||||||
|
assertThat(getRankingsWithForLoop(IMDB_TOP_MOVIES))
|
||||||
|
.containsExactly("1: The Shawshank Redemption",
|
||||||
|
"2: The Godfather", "3: The Godfather II", "4: The Dark Knight");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenRankings_whenCalculateWithForEachLoop_thenRankingsCorrect() {
|
||||||
|
assertThat(getRankingsWithForEachLoop(IMDB_TOP_MOVIES))
|
||||||
|
.containsExactly("1: The Shawshank Redemption",
|
||||||
|
"2: The Godfather", "3: The Godfather II", "4: The Dark Knight");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenRankings_whenCalculateWithFunctionalForEach_thenRankingsCorrect() {
|
||||||
|
assertThat(getRankingsWithFunctionalForEachLoop(IMDB_TOP_MOVIES))
|
||||||
|
.containsExactly("1: The Shawshank Redemption",
|
||||||
|
"2: The Godfather", "3: The Godfather II", "4: The Dark Knight");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenRankings_whenCalculateWithStream_thenRankingsCorrect() {
|
||||||
|
assertThat(getRankingsWithStream(IMDB_TOP_MOVIES.stream()))
|
||||||
|
.containsExactly("1: The Shawshank Redemption",
|
||||||
|
"2: The Godfather", "3: The Godfather II", "4: The Dark Knight");
|
||||||
|
}
|
||||||
|
}
|
@ -12,12 +12,20 @@
|
|||||||
<artifactId>core-java-lang-oop-types</artifactId>
|
<artifactId>core-java-lang-oop-types</artifactId>
|
||||||
<name>core-java-lang-oop-types</name>
|
<name>core-java-lang-oop-types</name>
|
||||||
<packaging>jar</packaging>
|
<packaging>jar</packaging>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.apache.commons</groupId>
|
<groupId>org.apache.commons</groupId>
|
||||||
<artifactId>commons-lang3</artifactId>
|
<artifactId>commons-lang3</artifactId>
|
||||||
<version>${commons-lang3.version}</version>
|
<version>${commons-lang3.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>commons-codec</groupId>
|
||||||
|
<artifactId>commons-codec</artifactId>
|
||||||
|
<version>${commons-codec.version}</version>
|
||||||
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
<properties>
|
||||||
|
<commons-codec.version>1.15</commons-codec.version>
|
||||||
|
</properties>
|
||||||
</project>
|
</project>
|
@ -0,0 +1,35 @@
|
|||||||
|
package com.baeldung.enums.extendenum;
|
||||||
|
|
||||||
|
import org.apache.commons.lang3.StringUtils;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.EnumMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
public class Application {
|
||||||
|
private static final Map<ImmutableOperation, Operator> OPERATION_MAP;
|
||||||
|
|
||||||
|
static {
|
||||||
|
OPERATION_MAP = new EnumMap<>(ImmutableOperation.class);
|
||||||
|
OPERATION_MAP.put(ImmutableOperation.TO_LOWER, String::toLowerCase);
|
||||||
|
OPERATION_MAP.put(ImmutableOperation.INVERT_CASE, StringUtils::swapCase);
|
||||||
|
OPERATION_MAP.put(ImmutableOperation.REMOVE_WHITESPACES, input -> input.replaceAll("\\s", ""));
|
||||||
|
|
||||||
|
if (Arrays.stream(ImmutableOperation.values()).anyMatch(it -> !OPERATION_MAP.containsKey(it))) {
|
||||||
|
throw new IllegalStateException("Unmapped enum constant found!");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public String applyImmutableOperation(ImmutableOperation operation, String input) {
|
||||||
|
return OPERATION_MAP.get(operation).apply(input);
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getDescription(StringOperation stringOperation) {
|
||||||
|
return stringOperation.getDescription();
|
||||||
|
}
|
||||||
|
|
||||||
|
public String applyOperation(StringOperation operation, String input) {
|
||||||
|
return operation.apply(input);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,26 @@
|
|||||||
|
package com.baeldung.enums.extendenum;
|
||||||
|
|
||||||
|
import org.apache.commons.lang3.StringUtils;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.EnumMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
public class ApplicationWithEx {
|
||||||
|
private static final Map<ImmutableOperation, Operator> OPERATION_MAP;
|
||||||
|
|
||||||
|
static {
|
||||||
|
OPERATION_MAP = new EnumMap<>(ImmutableOperation.class);
|
||||||
|
OPERATION_MAP.put(ImmutableOperation.TO_LOWER, String::toLowerCase);
|
||||||
|
OPERATION_MAP.put(ImmutableOperation.INVERT_CASE, StringUtils::swapCase);
|
||||||
|
// ImmutableOperation.REMOVE_WHITESPACES is not mapped
|
||||||
|
|
||||||
|
if (Arrays.stream(ImmutableOperation.values()).anyMatch(it -> !OPERATION_MAP.containsKey(it))) {
|
||||||
|
throw new IllegalStateException("Unmapped enum constant found!");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public String applyImmutableOperation(ImmutableOperation operation, String input) {
|
||||||
|
return OPERATION_MAP.get(operation).apply(input);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,33 @@
|
|||||||
|
package com.baeldung.enums.extendenum;
|
||||||
|
|
||||||
|
public enum BasicStringOperation implements StringOperation {
|
||||||
|
TRIM("Removing leading and trailing spaces.") {
|
||||||
|
@Override
|
||||||
|
public String apply(String input) {
|
||||||
|
return input.trim();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
TO_UPPER("Changing all characters into upper case.") {
|
||||||
|
@Override
|
||||||
|
public String apply(String input) {
|
||||||
|
return input.toUpperCase();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
REVERSE("Reversing the given string.") {
|
||||||
|
@Override
|
||||||
|
public String apply(String input) {
|
||||||
|
return new StringBuilder(input).reverse().toString();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
private String description;
|
||||||
|
|
||||||
|
public String getDescription() {
|
||||||
|
return description;
|
||||||
|
}
|
||||||
|
|
||||||
|
BasicStringOperation(String description) {
|
||||||
|
this.description = description;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,31 @@
|
|||||||
|
package com.baeldung.enums.extendenum;
|
||||||
|
|
||||||
|
import org.apache.commons.codec.binary.Base64;
|
||||||
|
import org.apache.commons.codec.digest.DigestUtils;
|
||||||
|
|
||||||
|
public enum ExtendedStringOperation implements StringOperation {
|
||||||
|
MD5_ENCODE("Encoding the given string using the MD5 algorithm.") {
|
||||||
|
@Override
|
||||||
|
public String apply(String input) {
|
||||||
|
return DigestUtils.md5Hex(input);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
BASE64_ENCODE("Encoding the given string using the BASE64 algorithm.") {
|
||||||
|
@Override
|
||||||
|
public String apply(String input) {
|
||||||
|
return new String(new Base64().encode(input.getBytes()));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
private String description;
|
||||||
|
|
||||||
|
ExtendedStringOperation(String description) {
|
||||||
|
this.description = description;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String getDescription() {
|
||||||
|
return description;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,6 @@
|
|||||||
|
package com.baeldung.enums.extendenum;
|
||||||
|
|
||||||
|
public enum ImmutableOperation {
|
||||||
|
REMOVE_WHITESPACES, TO_LOWER, INVERT_CASE
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,5 @@
|
|||||||
|
package com.baeldung.enums.extendenum;
|
||||||
|
|
||||||
|
public interface Operator {
|
||||||
|
String apply(String input);
|
||||||
|
}
|
@ -0,0 +1,7 @@
|
|||||||
|
package com.baeldung.enums.extendenum;
|
||||||
|
|
||||||
|
public interface StringOperation {
|
||||||
|
String getDescription();
|
||||||
|
|
||||||
|
String apply(String input);
|
||||||
|
}
|
@ -0,0 +1,43 @@
|
|||||||
|
package com.baeldung.enums.extendenum;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
public class ExtendEnumUnitTest {
|
||||||
|
private Application app = new Application();
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenAStringAndOperation_whenApplyOperation_thenGetExpectedResult() {
|
||||||
|
String input = " hello";
|
||||||
|
String expectedToUpper = " HELLO";
|
||||||
|
String expectedReverse = "olleh ";
|
||||||
|
String expectedTrim = "hello";
|
||||||
|
String expectedBase64 = "IGhlbGxv";
|
||||||
|
String expectedMd5 = "292a5af68d31c10e31ad449bd8f51263";
|
||||||
|
assertEquals(expectedTrim, app.applyOperation(BasicStringOperation.TRIM, input));
|
||||||
|
assertEquals(expectedToUpper, app.applyOperation(BasicStringOperation.TO_UPPER, input));
|
||||||
|
assertEquals(expectedReverse, app.applyOperation(BasicStringOperation.REVERSE, input));
|
||||||
|
assertEquals(expectedBase64, app.applyOperation(ExtendedStringOperation.BASE64_ENCODE, input));
|
||||||
|
assertEquals(expectedMd5, app.applyOperation(ExtendedStringOperation.MD5_ENCODE, input));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenAStringAndImmutableOperation_whenApplyOperation_thenGetExpectedResult() {
|
||||||
|
String input = " He ll O ";
|
||||||
|
String expectedToLower = " he ll o ";
|
||||||
|
String expectedRmWhitespace = "HellO";
|
||||||
|
String expectedInvertCase = " hE LL o ";
|
||||||
|
assertEquals(expectedToLower, app.applyImmutableOperation(ImmutableOperation.TO_LOWER, input));
|
||||||
|
assertEquals(expectedRmWhitespace, app.applyImmutableOperation(ImmutableOperation.REMOVE_WHITESPACES, input));
|
||||||
|
assertEquals(expectedInvertCase, app.applyImmutableOperation(ImmutableOperation.INVERT_CASE, input));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenUnmappedImmutableOperationValue_whenAppStarts_thenGetException() {
|
||||||
|
Throwable throwable = assertThrows(ExceptionInInitializerError.class, () -> {
|
||||||
|
ApplicationWithEx appEx = new ApplicationWithEx();
|
||||||
|
});
|
||||||
|
assertTrue(throwable.getCause() instanceof IllegalStateException);
|
||||||
|
}
|
||||||
|
}
|
8
core-java-modules/core-java-networking-3/README.md
Normal file
8
core-java-modules/core-java-networking-3/README.md
Normal file
@ -0,0 +1,8 @@
|
|||||||
|
## Core Java Networking (Part 3)
|
||||||
|
|
||||||
|
This module contains articles about networking in Java
|
||||||
|
|
||||||
|
### Relevant Articles
|
||||||
|
|
||||||
|
- TODO: add link once live
|
||||||
|
- [[<-- Prev]](/core-java-modules/core-java-networking-2)
|
59
core-java-modules/core-java-networking-3/pom.xml
Normal file
59
core-java-modules/core-java-networking-3/pom.xml
Normal file
@ -0,0 +1,59 @@
|
|||||||
|
<?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-networking-3</artifactId>
|
||||||
|
<name>core-java-networking-3</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.springframework</groupId>
|
||||||
|
<artifactId>spring-core</artifactId>
|
||||||
|
<version>${spring.core.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.eclipse.jetty</groupId>
|
||||||
|
<artifactId>jetty-server</artifactId>
|
||||||
|
<version>${jetty.embeded.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.tomcat.embed</groupId>
|
||||||
|
<artifactId>tomcat-embed-core</artifactId>
|
||||||
|
<version>${tomcat.embeded.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.assertj</groupId>
|
||||||
|
<artifactId>assertj-core</artifactId>
|
||||||
|
<version>${assertj.version}</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<finalName>core-java-networking-3</finalName>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<spring.core.version>5.2.8.RELEASE</spring.core.version>
|
||||||
|
<jetty.embeded.version>9.4.31.v20200723</jetty.embeded.version>
|
||||||
|
<tomcat.embeded.version>10.0.0-M7</tomcat.embeded.version>
|
||||||
|
<assertj.version>3.11.1</assertj.version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
|
</project>
|
@ -0,0 +1,150 @@
|
|||||||
|
package com.baeldung.socket;
|
||||||
|
|
||||||
|
import org.apache.catalina.LifecycleException;
|
||||||
|
import org.apache.catalina.startup.Tomcat;
|
||||||
|
import org.eclipse.jetty.server.Server;
|
||||||
|
import org.eclipse.jetty.server.ServerConnector;
|
||||||
|
import org.junit.jupiter.api.BeforeAll;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.springframework.util.SocketUtils;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.net.ServerSocket;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.*;
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
public class FindFreePortUnitTest {
|
||||||
|
|
||||||
|
private static int FREE_PORT_NUMBER;
|
||||||
|
private static int[] FREE_PORT_RANGE;
|
||||||
|
|
||||||
|
@BeforeAll
|
||||||
|
public static void getExplicitFreePortNumberAndRange() {
|
||||||
|
try (ServerSocket serverSocket = new ServerSocket(0)) {
|
||||||
|
FREE_PORT_NUMBER = serverSocket.getLocalPort();
|
||||||
|
FREE_PORT_RANGE = new int[] {FREE_PORT_NUMBER, FREE_PORT_NUMBER + 1, FREE_PORT_NUMBER + 2};
|
||||||
|
} catch (IOException e) {
|
||||||
|
fail("No free port is available");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenExplicitFreePort_whenCreatingServerSocket_thenThatPortIsAssigned() {
|
||||||
|
try (ServerSocket serverSocket = new ServerSocket(FREE_PORT_NUMBER)) {
|
||||||
|
assertThat(serverSocket).isNotNull();
|
||||||
|
assertThat(serverSocket.getLocalPort()).isEqualTo(FREE_PORT_NUMBER);
|
||||||
|
} catch (IOException e) {
|
||||||
|
fail("Port is not available");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenExplicitOccupiedPort_whenCreatingServerSocket_thenExceptionIsThrown() {
|
||||||
|
try (ServerSocket serverSocket = new ServerSocket(FREE_PORT_NUMBER)) {
|
||||||
|
new ServerSocket(FREE_PORT_NUMBER);
|
||||||
|
fail("Same port cannot be used twice");
|
||||||
|
} catch (IOException e) {
|
||||||
|
assertThat(e).hasMessageContaining("Address already in use");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenExplicitPortRange_whenCreatingServerSocket_thenOnePortIsAssigned() {
|
||||||
|
for (int port : FREE_PORT_RANGE) {
|
||||||
|
try (ServerSocket serverSocket = new ServerSocket(port)) {
|
||||||
|
assertThat(serverSocket).isNotNull();
|
||||||
|
assertThat(serverSocket.getLocalPort()).isEqualTo(port);
|
||||||
|
return;
|
||||||
|
} catch (IOException e) {
|
||||||
|
assertThat(e).hasMessageContaining("Address already in use");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fail("No free port in the range found");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenPortZero_whenCreatingServerSocket_thenFreePortIsAssigned() {
|
||||||
|
try (ServerSocket serverSocket = new ServerSocket(0)) {
|
||||||
|
assertThat(serverSocket).isNotNull();
|
||||||
|
assertThat(serverSocket.getLocalPort()).isGreaterThan(0);
|
||||||
|
} catch (IOException e) {
|
||||||
|
fail("Port is not available");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenAvailableTcpPort_whenCreatingServerSocket_thenThatPortIsAssigned() {
|
||||||
|
int port = SocketUtils.findAvailableTcpPort();
|
||||||
|
try (ServerSocket serverSocket = new ServerSocket(port)) {
|
||||||
|
assertThat(serverSocket).isNotNull();
|
||||||
|
assertThat(serverSocket.getLocalPort()).isEqualTo(port);
|
||||||
|
} catch (IOException e) {
|
||||||
|
fail("Port is not available");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenNoPortDefined_whenCreatingJettyServer_thenFreePortIsAssigned() throws Exception {
|
||||||
|
Server jettyServer = new Server();
|
||||||
|
ServerConnector serverConnector = new ServerConnector(jettyServer);
|
||||||
|
jettyServer.addConnector(serverConnector);
|
||||||
|
try {
|
||||||
|
jettyServer.start();
|
||||||
|
assertThat(serverConnector.getLocalPort()).isGreaterThan(0);
|
||||||
|
} catch (Exception e) {
|
||||||
|
fail("Failed to start Jetty server");
|
||||||
|
} finally {
|
||||||
|
jettyServer.stop();
|
||||||
|
jettyServer.destroy();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenExplicitFreePort_whenCreatingJettyServer_thenThatPortIsAssigned() throws Exception {
|
||||||
|
Server jettyServer = new Server();
|
||||||
|
ServerConnector serverConnector = new ServerConnector(jettyServer);
|
||||||
|
serverConnector.setPort(FREE_PORT_NUMBER);
|
||||||
|
jettyServer.addConnector(serverConnector);
|
||||||
|
try {
|
||||||
|
jettyServer.start();
|
||||||
|
assertThat(serverConnector.getLocalPort()).isEqualTo(FREE_PORT_NUMBER);
|
||||||
|
} catch (Exception e) {
|
||||||
|
fail("Failed to start Jetty server");
|
||||||
|
} finally {
|
||||||
|
jettyServer.stop();
|
||||||
|
jettyServer.destroy();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenPortZero_whenCreatingTomcatServer_thenFreePortIsAssigned() throws Exception {
|
||||||
|
Tomcat tomcatServer = new Tomcat();
|
||||||
|
tomcatServer.setPort(0);
|
||||||
|
try {
|
||||||
|
tomcatServer.start();
|
||||||
|
assertThat(tomcatServer.getConnector().getLocalPort()).isGreaterThan(0);
|
||||||
|
} catch (LifecycleException e) {
|
||||||
|
fail("Failed to start Tomcat server");
|
||||||
|
} finally {
|
||||||
|
tomcatServer.stop();
|
||||||
|
tomcatServer.destroy();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenExplicitFreePort_whenCreatingTomcatServer_thenThatPortIsAssigned() throws Exception {
|
||||||
|
Tomcat tomcatServer = new Tomcat();
|
||||||
|
tomcatServer.setPort(FREE_PORT_NUMBER);
|
||||||
|
try {
|
||||||
|
tomcatServer.start();
|
||||||
|
assertThat(tomcatServer.getConnector().getLocalPort()).isEqualTo(FREE_PORT_NUMBER);
|
||||||
|
} catch (LifecycleException e) {
|
||||||
|
fail("Failed to start Tomcat server");
|
||||||
|
} finally {
|
||||||
|
tomcatServer.stop();
|
||||||
|
tomcatServer.destroy();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -8,5 +8,5 @@ This module contains articles about string APIs.
|
|||||||
- [Guide to java.util.Formatter](https://www.baeldung.com/java-string-formatter)
|
- [Guide to java.util.Formatter](https://www.baeldung.com/java-string-formatter)
|
||||||
- [Guide to StreamTokenizer](https://www.baeldung.com/java-streamtokenizer)
|
- [Guide to StreamTokenizer](https://www.baeldung.com/java-streamtokenizer)
|
||||||
- [CharSequence vs. String in Java](https://www.baeldung.com/java-char-sequence-string)
|
- [CharSequence vs. String in Java](https://www.baeldung.com/java-char-sequence-string)
|
||||||
- [StringBuilder and StringBuffer in Java](https://www.baeldung.com/java-string-builder-string-buffer)
|
- [StringBuilder vs StringBuffer in Java](https://www.baeldung.com/java-string-builder-string-buffer)
|
||||||
- [Generate a Secure Random Password in Java](https://www.baeldung.com/java-generate-secure-password)
|
- [Generate a Secure Random Password in Java](https://www.baeldung.com/java-generate-secure-password)
|
||||||
|
@ -29,7 +29,8 @@
|
|||||||
<module>core-java-arrays-convert</module>
|
<module>core-java-arrays-convert</module>
|
||||||
<module>core-java-arrays-operations-basic</module>
|
<module>core-java-arrays-operations-basic</module>
|
||||||
<module>core-java-arrays-operations-advanced</module>
|
<module>core-java-arrays-operations-advanced</module>
|
||||||
|
|
||||||
|
<module>core-java-char</module>
|
||||||
<module>core-java-collections</module>
|
<module>core-java-collections</module>
|
||||||
<module>core-java-collections-2</module>
|
<module>core-java-collections-2</module>
|
||||||
<module>core-java-collections-3</module>
|
<module>core-java-collections-3</module>
|
||||||
|
@ -1,11 +0,0 @@
|
|||||||
## Core Kotlin Advanced
|
|
||||||
|
|
||||||
This module contains articles about advanced topics in Kotlin.
|
|
||||||
|
|
||||||
### Relevant articles:
|
|
||||||
- [Building DSLs in Kotlin](https://www.baeldung.com/kotlin-dsl)
|
|
||||||
- [Regular Expressions in Kotlin](https://www.baeldung.com/kotlin-regular-expressions)
|
|
||||||
- [Idiomatic Logging in Kotlin](https://www.baeldung.com/kotlin-logging)
|
|
||||||
- [Mapping of Data Objects in Kotlin](https://www.baeldung.com/kotlin-data-objects)
|
|
||||||
- [Reflection with Kotlin](https://www.baeldung.com/kotlin-reflection)
|
|
||||||
- [Kotlin Contracts](https://www.baeldung.com/kotlin-contracts)
|
|
@ -1,41 +0,0 @@
|
|||||||
<?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-kotlin-advanced</artifactId>
|
|
||||||
<name>core-kotlin-advanced</name>
|
|
||||||
<packaging>jar</packaging>
|
|
||||||
|
|
||||||
<parent>
|
|
||||||
<groupId>com.baeldung.core-kotlin-modules</groupId>
|
|
||||||
<artifactId>core-kotlin-modules</artifactId>
|
|
||||||
<version>1.0.0-SNAPSHOT</version>
|
|
||||||
</parent>
|
|
||||||
|
|
||||||
<dependencies>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.jetbrains.kotlin</groupId>
|
|
||||||
<artifactId>kotlin-stdlib-jdk8</artifactId>
|
|
||||||
<version>${kotlin.version}</version>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.assertj</groupId>
|
|
||||||
<artifactId>assertj-core</artifactId>
|
|
||||||
<version>${assertj.version}</version>
|
|
||||||
<scope>test</scope>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.jetbrains.kotlin</groupId>
|
|
||||||
<artifactId>kotlin-test</artifactId>
|
|
||||||
<version>${kotlin.version}</version>
|
|
||||||
<scope>test</scope>
|
|
||||||
</dependency>
|
|
||||||
</dependencies>
|
|
||||||
|
|
||||||
<properties>
|
|
||||||
<kotlin.version>1.3.30</kotlin.version>
|
|
||||||
<assertj.version>3.10.0</assertj.version>
|
|
||||||
</properties>
|
|
||||||
|
|
||||||
</project>
|
|
@ -1,23 +0,0 @@
|
|||||||
package com.baeldung.contract
|
|
||||||
|
|
||||||
import kotlin.contracts.ExperimentalContracts
|
|
||||||
import kotlin.contracts.InvocationKind
|
|
||||||
import kotlin.contracts.contract
|
|
||||||
|
|
||||||
@ExperimentalContracts
|
|
||||||
inline fun <R> myRun(block: () -> R): R {
|
|
||||||
contract {
|
|
||||||
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
|
|
||||||
}
|
|
||||||
return block()
|
|
||||||
}
|
|
||||||
|
|
||||||
@ExperimentalContracts
|
|
||||||
fun callsInPlace() {
|
|
||||||
val i: Int
|
|
||||||
myRun {
|
|
||||||
i = 1 // Without contract initialization is forbidden due to possible re-assignment
|
|
||||||
}
|
|
||||||
println(i) // Without contract variable might be uninitialized
|
|
||||||
}
|
|
||||||
|
|
@ -1,43 +0,0 @@
|
|||||||
package com.baeldung.contract
|
|
||||||
|
|
||||||
import kotlin.contracts.ExperimentalContracts
|
|
||||||
import kotlin.contracts.contract
|
|
||||||
|
|
||||||
data class Request(val arg: String)
|
|
||||||
|
|
||||||
class Service {
|
|
||||||
|
|
||||||
@ExperimentalContracts
|
|
||||||
fun process(request: Request?) {
|
|
||||||
validate(request)
|
|
||||||
println(request.arg)
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
@ExperimentalContracts
|
|
||||||
private fun validate(request: Request?) {
|
|
||||||
contract {
|
|
||||||
returns() implies (request != null)
|
|
||||||
}
|
|
||||||
if (request == null) {
|
|
||||||
throw IllegalArgumentException("Undefined request")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
data class MyEvent(val message: String)
|
|
||||||
|
|
||||||
@ExperimentalContracts
|
|
||||||
fun processEvent(event: Any?) {
|
|
||||||
if (isInterested(event)) {
|
|
||||||
println(event.message) // Compiler makes smart cast here with the help of contract
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@ExperimentalContracts
|
|
||||||
fun isInterested(event: Any?): Boolean {
|
|
||||||
contract {
|
|
||||||
returns(true) implies (event is MyEvent)
|
|
||||||
}
|
|
||||||
return event is MyEvent
|
|
||||||
}
|
|
@ -1,10 +0,0 @@
|
|||||||
package com.baeldung.datamapping
|
|
||||||
|
|
||||||
data class User(
|
|
||||||
val firstName: String,
|
|
||||||
val lastName: String,
|
|
||||||
val street: String,
|
|
||||||
val houseNumber: String,
|
|
||||||
val phone: String,
|
|
||||||
val age: Int,
|
|
||||||
val password: String)
|
|
@ -1,22 +0,0 @@
|
|||||||
package com.baeldung.datamapping
|
|
||||||
|
|
||||||
import kotlin.reflect.full.memberProperties
|
|
||||||
|
|
||||||
fun User.toUserView() = UserView(
|
|
||||||
name = "$firstName $lastName",
|
|
||||||
address = "$street $houseNumber",
|
|
||||||
telephone = phone,
|
|
||||||
age = age
|
|
||||||
)
|
|
||||||
|
|
||||||
fun User.toUserViewReflection() = with(::UserView) {
|
|
||||||
val propertiesByName = User::class.memberProperties.associateBy { it.name }
|
|
||||||
callBy(parameters.associate { parameter ->
|
|
||||||
parameter to when (parameter.name) {
|
|
||||||
UserView::name.name -> "$firstName $lastName"
|
|
||||||
UserView::address.name -> "$street $houseNumber"
|
|
||||||
UserView::telephone.name -> phone
|
|
||||||
else -> propertiesByName[parameter.name]?.get(this@toUserViewReflection)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
@ -1,8 +0,0 @@
|
|||||||
package com.baeldung.datamapping
|
|
||||||
|
|
||||||
data class UserView(
|
|
||||||
val name: String,
|
|
||||||
val address: String,
|
|
||||||
val telephone: String,
|
|
||||||
val age: Int
|
|
||||||
)
|
|
@ -1,114 +0,0 @@
|
|||||||
package com.baeldung.dsl
|
|
||||||
|
|
||||||
abstract class Condition {
|
|
||||||
|
|
||||||
fun and(initializer: Condition.() -> Unit) {
|
|
||||||
addCondition(And().apply(initializer))
|
|
||||||
}
|
|
||||||
|
|
||||||
fun or(initializer: Condition.() -> Unit) {
|
|
||||||
addCondition(Or().apply(initializer))
|
|
||||||
}
|
|
||||||
|
|
||||||
infix fun String.eq(value: Any?) {
|
|
||||||
addCondition(Eq(this, value))
|
|
||||||
}
|
|
||||||
|
|
||||||
protected abstract fun addCondition(condition: Condition)
|
|
||||||
}
|
|
||||||
|
|
||||||
open class CompositeCondition(private val sqlOperator: String) : Condition() {
|
|
||||||
private val conditions = mutableListOf<Condition>()
|
|
||||||
|
|
||||||
override fun addCondition(condition: Condition) {
|
|
||||||
conditions += condition
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun toString(): String {
|
|
||||||
return if (conditions.size == 1) {
|
|
||||||
conditions.first().toString()
|
|
||||||
} else {
|
|
||||||
conditions.joinToString(prefix = "(", postfix = ")", separator = " $sqlOperator ") {
|
|
||||||
"$it"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
class And : CompositeCondition("and")
|
|
||||||
|
|
||||||
class Or : CompositeCondition("or")
|
|
||||||
|
|
||||||
class Eq(private val column: String, private val value: Any?) : Condition() {
|
|
||||||
|
|
||||||
init {
|
|
||||||
if (value != null && value !is Number && value !is String) {
|
|
||||||
throw IllegalArgumentException("Only <null>, numbers and strings values can be used in the 'where' clause")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun addCondition(condition: Condition) {
|
|
||||||
throw IllegalStateException("Can't add a nested condition to the sql 'eq'")
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun toString(): String {
|
|
||||||
return when (value) {
|
|
||||||
null -> "$column is null"
|
|
||||||
is String -> "$column = '$value'"
|
|
||||||
else -> "$column = $value"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
class SqlSelectBuilder {
|
|
||||||
|
|
||||||
private val columns = mutableListOf<String>()
|
|
||||||
private lateinit var table: String
|
|
||||||
private var condition: Condition? = null
|
|
||||||
|
|
||||||
fun select(vararg columns: String) {
|
|
||||||
if (columns.isEmpty()) {
|
|
||||||
throw IllegalArgumentException("At least one column should be defined")
|
|
||||||
}
|
|
||||||
if (this.columns.isNotEmpty()) {
|
|
||||||
throw IllegalStateException("Detected an attempt to re-define columns to fetch. Current columns list: "
|
|
||||||
+ "${this.columns}, new columns list: $columns")
|
|
||||||
}
|
|
||||||
this.columns.addAll(columns)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun from(table: String) {
|
|
||||||
this.table = table
|
|
||||||
}
|
|
||||||
|
|
||||||
fun where(initializer: Condition.() -> Unit) {
|
|
||||||
condition = And().apply(initializer)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun build(): String {
|
|
||||||
if (!::table.isInitialized) {
|
|
||||||
throw IllegalStateException("Failed to build an sql select - target table is undefined")
|
|
||||||
}
|
|
||||||
return toString()
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun toString(): String {
|
|
||||||
val columnsToFetch =
|
|
||||||
if (columns.isEmpty()) {
|
|
||||||
"*"
|
|
||||||
} else {
|
|
||||||
columns.joinToString(", ")
|
|
||||||
}
|
|
||||||
val conditionString =
|
|
||||||
if (condition == null) {
|
|
||||||
""
|
|
||||||
} else {
|
|
||||||
" where $condition"
|
|
||||||
}
|
|
||||||
return "select $columnsToFetch from $table$conditionString"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun query(initializer: SqlSelectBuilder.() -> Unit): SqlSelectBuilder {
|
|
||||||
return SqlSelectBuilder().apply(initializer)
|
|
||||||
}
|
|
@ -1,30 +0,0 @@
|
|||||||
package com.baeldung.logging
|
|
||||||
|
|
||||||
import org.slf4j.Logger
|
|
||||||
|
|
||||||
open class LoggerAsExtensionOnAny {
|
|
||||||
val logger = logger()
|
|
||||||
|
|
||||||
fun log(s: String) {
|
|
||||||
logger().info(s)
|
|
||||||
logger.info(s)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
class ExtensionSubclass : LoggerAsExtensionOnAny()
|
|
||||||
|
|
||||||
fun <T : Any> T.logger(): Logger = getLogger(getClassForLogging(javaClass))
|
|
||||||
|
|
||||||
fun main(args: Array<String>) {
|
|
||||||
LoggerAsExtensionOnAny().log("test")
|
|
||||||
ExtensionSubclass().log("sub")
|
|
||||||
"foo".logger().info("foo")
|
|
||||||
1.logger().info("uh-oh!")
|
|
||||||
SomeOtherClass().logger()
|
|
||||||
}
|
|
||||||
|
|
||||||
class SomeOtherClass {
|
|
||||||
fun logger(): String {
|
|
||||||
return "foo"
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,30 +0,0 @@
|
|||||||
package com.baeldung.logging
|
|
||||||
|
|
||||||
import org.slf4j.Logger
|
|
||||||
import org.slf4j.LoggerFactory
|
|
||||||
|
|
||||||
interface Logging
|
|
||||||
|
|
||||||
inline fun <reified T : Logging> T.logger(): Logger =
|
|
||||||
//Wrong logger name!
|
|
||||||
//LoggerFactory.getLogger(javaClass.name + " w/interface")
|
|
||||||
LoggerFactory.getLogger(getClassForLogging(T::class.java).name + " w/interface")
|
|
||||||
|
|
||||||
open class LoggerAsExtensionOnMarkerInterface : Logging {
|
|
||||||
companion object : Logging {
|
|
||||||
val logger = logger()
|
|
||||||
}
|
|
||||||
|
|
||||||
fun log(s: String) {
|
|
||||||
logger().info(s)
|
|
||||||
logger.info(s)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
class MarkerExtensionSubclass : LoggerAsExtensionOnMarkerInterface()
|
|
||||||
|
|
||||||
fun main(args: Array<String>) {
|
|
||||||
LoggerAsExtensionOnMarkerInterface().log("test")
|
|
||||||
MarkerExtensionSubclass().log("sub")
|
|
||||||
"foo".logger().info("foo")
|
|
||||||
}
|
|
@ -1,17 +0,0 @@
|
|||||||
package com.baeldung.logging
|
|
||||||
|
|
||||||
open class LoggerAsProperty {
|
|
||||||
private val logger = getLogger(javaClass)
|
|
||||||
|
|
||||||
fun log(s: String) {
|
|
||||||
logger.info(s)
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
class PropertySubclass : LoggerAsProperty()
|
|
||||||
|
|
||||||
fun main(args: Array<String>) {
|
|
||||||
LoggerAsProperty().log("test")
|
|
||||||
PropertySubclass().log("sub")
|
|
||||||
}
|
|
@ -1,47 +0,0 @@
|
|||||||
package com.baeldung.logging
|
|
||||||
|
|
||||||
import org.slf4j.Logger
|
|
||||||
import kotlin.properties.ReadOnlyProperty
|
|
||||||
import kotlin.reflect.KProperty
|
|
||||||
|
|
||||||
open class LoggerAsPropertyDelegate {
|
|
||||||
private val lazyLogger by lazyLogger()
|
|
||||||
protected val logger by LoggerDelegate()
|
|
||||||
private val logger2 = logger
|
|
||||||
|
|
||||||
companion object {
|
|
||||||
private val lazyLoggerComp by lazyLogger()
|
|
||||||
private val loggerComp by LoggerDelegate()
|
|
||||||
}
|
|
||||||
|
|
||||||
open fun log(s: String) {
|
|
||||||
logger.info(s)
|
|
||||||
logger2.info(s)
|
|
||||||
lazyLogger.info(s)
|
|
||||||
loggerComp.info(s)
|
|
||||||
lazyLoggerComp.info(s)
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
class DelegateSubclass : LoggerAsPropertyDelegate() {
|
|
||||||
override fun log(s: String) {
|
|
||||||
logger.info("-- in sub")
|
|
||||||
super.log(s)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun lazyLogger(forClass: Class<*>): Lazy<Logger> =
|
|
||||||
lazy { getLogger(getClassForLogging(forClass)) }
|
|
||||||
|
|
||||||
fun <T : Any> T.lazyLogger(): Lazy<Logger> = lazyLogger(javaClass)
|
|
||||||
|
|
||||||
fun main(args: Array<String>) {
|
|
||||||
LoggerAsPropertyDelegate().log("test")
|
|
||||||
DelegateSubclass().log("sub")
|
|
||||||
}
|
|
||||||
|
|
||||||
class LoggerDelegate<in R : Any> : ReadOnlyProperty<R, Logger> {
|
|
||||||
override fun getValue(thisRef: R, property: KProperty<*>) =
|
|
||||||
getLogger(getClassForLogging(thisRef.javaClass))
|
|
||||||
}
|
|
@ -1,44 +0,0 @@
|
|||||||
package com.baeldung.logging
|
|
||||||
|
|
||||||
open class LoggerInCompanionObject {
|
|
||||||
companion object {
|
|
||||||
private val loggerWithExplicitClass = getLogger(LoggerInCompanionObject::class.java)
|
|
||||||
@Suppress("JAVA_CLASS_ON_COMPANION")
|
|
||||||
private val loggerWithWrongClass = getLogger(javaClass)
|
|
||||||
@Suppress("JAVA_CLASS_ON_COMPANION")
|
|
||||||
private val logger = getLogger(javaClass.enclosingClass)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun log(s: String) {
|
|
||||||
loggerWithExplicitClass.info(s)
|
|
||||||
loggerWithWrongClass.info(s)
|
|
||||||
logger.info(s)
|
|
||||||
}
|
|
||||||
|
|
||||||
class Inner {
|
|
||||||
companion object {
|
|
||||||
private val loggerWithExplicitClass = getLogger(Inner::class.java)
|
|
||||||
@Suppress("JAVA_CLASS_ON_COMPANION")
|
|
||||||
@JvmStatic
|
|
||||||
private val loggerWithWrongClass = getLogger(javaClass)
|
|
||||||
@Suppress("JAVA_CLASS_ON_COMPANION")
|
|
||||||
@JvmStatic
|
|
||||||
private val logger = getLogger(javaClass.enclosingClass)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun log(s: String) {
|
|
||||||
loggerWithExplicitClass.info(s)
|
|
||||||
loggerWithWrongClass.info(s)
|
|
||||||
logger.info(s)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
class CompanionSubclass : LoggerInCompanionObject()
|
|
||||||
|
|
||||||
fun main(args: Array<String>) {
|
|
||||||
LoggerInCompanionObject().log("test")
|
|
||||||
LoggerInCompanionObject.Inner().log("test")
|
|
||||||
CompanionSubclass().log("sub")
|
|
||||||
}
|
|
@ -1,13 +0,0 @@
|
|||||||
package com.baeldung.logging
|
|
||||||
|
|
||||||
import org.slf4j.Logger
|
|
||||||
import org.slf4j.LoggerFactory
|
|
||||||
import kotlin.reflect.full.companionObject
|
|
||||||
|
|
||||||
fun getLogger(forClass: Class<*>): Logger = LoggerFactory.getLogger(forClass)
|
|
||||||
|
|
||||||
fun <T : Any> getClassForLogging(javaClass: Class<T>): Class<*> {
|
|
||||||
return javaClass.enclosingClass?.takeIf {
|
|
||||||
it.kotlin.companionObject?.java == javaClass
|
|
||||||
} ?: javaClass
|
|
||||||
}
|
|
@ -1,43 +0,0 @@
|
|||||||
package com.baeldung.datamapping
|
|
||||||
|
|
||||||
import org.junit.jupiter.api.Test
|
|
||||||
import org.junit.jupiter.api.assertAll
|
|
||||||
import kotlin.test.assertEquals
|
|
||||||
|
|
||||||
class UserTest {
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun `maps User to UserResponse using extension function`() {
|
|
||||||
val p = buildUser()
|
|
||||||
val view = p.toUserView()
|
|
||||||
assertUserView(view)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun `maps User to UserResponse using reflection`() {
|
|
||||||
val p = buildUser()
|
|
||||||
val view = p.toUserViewReflection()
|
|
||||||
assertUserView(view)
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun buildUser(): User {
|
|
||||||
return User(
|
|
||||||
"Java",
|
|
||||||
"Duke",
|
|
||||||
"Javastreet",
|
|
||||||
"42",
|
|
||||||
"1234567",
|
|
||||||
30,
|
|
||||||
"s3cr37"
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun assertUserView(pr: UserView) {
|
|
||||||
assertAll(
|
|
||||||
{ assertEquals("Java Duke", pr.name) },
|
|
||||||
{ assertEquals("Javastreet 42", pr.address) },
|
|
||||||
{ assertEquals("1234567", pr.telephone) },
|
|
||||||
{ assertEquals(30, pr.age) }
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,73 +0,0 @@
|
|||||||
package com.baeldung.dsl
|
|
||||||
|
|
||||||
import org.assertj.core.api.Assertions.assertThat
|
|
||||||
import org.junit.Test
|
|
||||||
|
|
||||||
class SqlDslTest {
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun `when no columns are specified then star is used`() {
|
|
||||||
doTest("select * from table1") {
|
|
||||||
from ("table1")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun `when no condition is specified then correct query is built`() {
|
|
||||||
doTest("select column1, column2 from table1") {
|
|
||||||
select("column1", "column2")
|
|
||||||
from ("table1")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test(expected = Exception::class)
|
|
||||||
fun `when no table is specified then an exception is thrown`() {
|
|
||||||
query {
|
|
||||||
select("column1")
|
|
||||||
}.build()
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun `when a list of conditions is specified then it's respected`() {
|
|
||||||
doTest("select * from table1 where (column3 = 4 and column4 is null)") {
|
|
||||||
from ("table1")
|
|
||||||
where {
|
|
||||||
"column3" eq 4
|
|
||||||
"column4" eq null
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun `when 'or' conditions are specified then they are respected`() {
|
|
||||||
doTest("select * from table1 where (column3 = 4 or column4 is null)") {
|
|
||||||
from ("table1")
|
|
||||||
where {
|
|
||||||
or {
|
|
||||||
"column3" eq 4
|
|
||||||
"column4" eq null
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun `when either 'and' or 'or' conditions are specified then they are respected`() {
|
|
||||||
doTest("select * from table1 where ((column3 = 4 or column4 is null) and column5 = 42)") {
|
|
||||||
from ("table1")
|
|
||||||
where {
|
|
||||||
and {
|
|
||||||
or {
|
|
||||||
"column3" eq 4
|
|
||||||
"column4" eq null
|
|
||||||
}
|
|
||||||
"column5" eq 42
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun doTest(expected: String, sql: SqlSelectBuilder.() -> Unit) {
|
|
||||||
assertThat(query(sql).build()).isEqualTo(expected)
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,32 +0,0 @@
|
|||||||
package com.baeldung.reflection
|
|
||||||
|
|
||||||
import org.junit.Ignore
|
|
||||||
import org.junit.Test
|
|
||||||
import org.slf4j.LoggerFactory
|
|
||||||
|
|
||||||
@Ignore
|
|
||||||
class JavaReflectionTest {
|
|
||||||
private val LOG = LoggerFactory.getLogger(KClassTest::class.java)
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun listJavaClassMethods() {
|
|
||||||
Exception::class.java.methods
|
|
||||||
.forEach { method -> LOG.info("Method: {}", method) }
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun listKotlinClassMethods() {
|
|
||||||
JavaReflectionTest::class.java.methods
|
|
||||||
.forEach { method -> LOG.info("Method: {}", method) }
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun listKotlinDataClassMethods() {
|
|
||||||
data class ExampleDataClass(val name: String, var enabled: Boolean)
|
|
||||||
|
|
||||||
ExampleDataClass::class.java.methods
|
|
||||||
.forEach { method -> LOG.info("Method: {}", method) }
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
}
|
|
@ -1,69 +0,0 @@
|
|||||||
package com.baeldung.reflection
|
|
||||||
|
|
||||||
import org.junit.Assert
|
|
||||||
import org.junit.Ignore
|
|
||||||
import org.junit.Test
|
|
||||||
import org.slf4j.LoggerFactory
|
|
||||||
import java.math.BigDecimal
|
|
||||||
import kotlin.reflect.full.*
|
|
||||||
|
|
||||||
class KClassTest {
|
|
||||||
private val LOG = LoggerFactory.getLogger(KClassTest::class.java)
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun testKClassDetails() {
|
|
||||||
val stringClass = String::class
|
|
||||||
Assert.assertEquals("kotlin.String", stringClass.qualifiedName)
|
|
||||||
Assert.assertFalse(stringClass.isData)
|
|
||||||
Assert.assertFalse(stringClass.isCompanion)
|
|
||||||
Assert.assertFalse(stringClass.isAbstract)
|
|
||||||
Assert.assertTrue(stringClass.isFinal)
|
|
||||||
Assert.assertFalse(stringClass.isSealed)
|
|
||||||
|
|
||||||
val listClass = List::class
|
|
||||||
Assert.assertEquals("kotlin.collections.List", listClass.qualifiedName)
|
|
||||||
Assert.assertFalse(listClass.isData)
|
|
||||||
Assert.assertFalse(listClass.isCompanion)
|
|
||||||
Assert.assertTrue(listClass.isAbstract)
|
|
||||||
Assert.assertFalse(listClass.isFinal)
|
|
||||||
Assert.assertFalse(listClass.isSealed)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun testGetRelated() {
|
|
||||||
LOG.info("Companion Object: {}", TestSubject::class.companionObject)
|
|
||||||
LOG.info("Companion Object Instance: {}", TestSubject::class.companionObjectInstance)
|
|
||||||
LOG.info("Object Instance: {}", TestObject::class.objectInstance)
|
|
||||||
|
|
||||||
Assert.assertSame(TestObject, TestObject::class.objectInstance)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun testNewInstance() {
|
|
||||||
val listClass = ArrayList::class
|
|
||||||
|
|
||||||
val list = listClass.createInstance()
|
|
||||||
Assert.assertTrue(list is ArrayList)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
@Ignore
|
|
||||||
fun testMembers() {
|
|
||||||
val bigDecimalClass = BigDecimal::class
|
|
||||||
|
|
||||||
LOG.info("Constructors: {}", bigDecimalClass.constructors)
|
|
||||||
LOG.info("Functions: {}", bigDecimalClass.functions)
|
|
||||||
LOG.info("Properties: {}", bigDecimalClass.memberProperties)
|
|
||||||
LOG.info("Extension Functions: {}", bigDecimalClass.memberExtensionFunctions)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
class TestSubject {
|
|
||||||
companion object {
|
|
||||||
val name = "TestSubject"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
object TestObject {
|
|
||||||
val answer = 42
|
|
||||||
}
|
|
@ -1,88 +0,0 @@
|
|||||||
package com.baeldung.reflection
|
|
||||||
|
|
||||||
import org.junit.Assert
|
|
||||||
import org.junit.Test
|
|
||||||
import java.io.ByteArrayInputStream
|
|
||||||
import java.nio.charset.Charset
|
|
||||||
import kotlin.reflect.KMutableProperty
|
|
||||||
import kotlin.reflect.full.starProjectedType
|
|
||||||
|
|
||||||
class KMethodTest {
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun testCallMethod() {
|
|
||||||
val str = "Hello"
|
|
||||||
val lengthMethod = str::length
|
|
||||||
|
|
||||||
Assert.assertEquals(5, lengthMethod())
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun testReturnType() {
|
|
||||||
val str = "Hello"
|
|
||||||
val method = str::byteInputStream
|
|
||||||
|
|
||||||
Assert.assertEquals(ByteArrayInputStream::class.starProjectedType, method.returnType)
|
|
||||||
Assert.assertFalse(method.returnType.isMarkedNullable)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun testParams() {
|
|
||||||
val str = "Hello"
|
|
||||||
val method = str::byteInputStream
|
|
||||||
|
|
||||||
method.isSuspend
|
|
||||||
Assert.assertEquals(1, method.parameters.size)
|
|
||||||
Assert.assertTrue(method.parameters[0].isOptional)
|
|
||||||
Assert.assertFalse(method.parameters[0].isVararg)
|
|
||||||
Assert.assertEquals(Charset::class.starProjectedType, method.parameters[0].type)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun testMethodDetails() {
|
|
||||||
val codePoints = String::codePoints
|
|
||||||
Assert.assertEquals("codePoints", codePoints.name)
|
|
||||||
Assert.assertFalse(codePoints.isSuspend)
|
|
||||||
Assert.assertFalse(codePoints.isExternal)
|
|
||||||
Assert.assertFalse(codePoints.isInline)
|
|
||||||
Assert.assertFalse(codePoints.isOperator)
|
|
||||||
|
|
||||||
val byteInputStream = String::byteInputStream
|
|
||||||
Assert.assertEquals("byteInputStream", byteInputStream.name)
|
|
||||||
Assert.assertFalse(byteInputStream.isSuspend)
|
|
||||||
Assert.assertFalse(byteInputStream.isExternal)
|
|
||||||
Assert.assertTrue(byteInputStream.isInline)
|
|
||||||
Assert.assertFalse(byteInputStream.isOperator)
|
|
||||||
}
|
|
||||||
|
|
||||||
val readOnlyProperty: Int = 42
|
|
||||||
lateinit var mutableProperty: String
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun testPropertyDetails() {
|
|
||||||
val roProperty = this::readOnlyProperty
|
|
||||||
Assert.assertEquals("readOnlyProperty", roProperty.name)
|
|
||||||
Assert.assertFalse(roProperty.isLateinit)
|
|
||||||
Assert.assertFalse(roProperty.isConst)
|
|
||||||
Assert.assertFalse(roProperty is KMutableProperty<*>)
|
|
||||||
|
|
||||||
val mProperty = this::mutableProperty
|
|
||||||
Assert.assertEquals("mutableProperty", mProperty.name)
|
|
||||||
Assert.assertTrue(mProperty.isLateinit)
|
|
||||||
Assert.assertFalse(mProperty.isConst)
|
|
||||||
Assert.assertTrue(mProperty is KMutableProperty<*>)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun testProperty() {
|
|
||||||
val prop = this::mutableProperty
|
|
||||||
|
|
||||||
Assert.assertEquals(String::class.starProjectedType, prop.getter.returnType)
|
|
||||||
|
|
||||||
prop.set("Hello")
|
|
||||||
Assert.assertEquals("Hello", prop.get())
|
|
||||||
|
|
||||||
prop.setter("World")
|
|
||||||
Assert.assertEquals("World", prop.getter())
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,123 +0,0 @@
|
|||||||
package com.baeldung.regex
|
|
||||||
|
|
||||||
import org.junit.Test
|
|
||||||
import kotlin.test.*
|
|
||||||
|
|
||||||
class RegexTest {
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun whenRegexIsInstantiated_thenIsEqualToToRegexMethod() {
|
|
||||||
val pattern = """a([bc]+)d?\\"""
|
|
||||||
|
|
||||||
assertEquals(Regex.fromLiteral(pattern).pattern, pattern)
|
|
||||||
assertEquals(pattern, Regex(pattern).pattern)
|
|
||||||
assertEquals(pattern, pattern.toRegex().pattern)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun whenRegexMatches_thenResultIsTrue() {
|
|
||||||
val regex = """a([bc]+)d?""".toRegex()
|
|
||||||
|
|
||||||
assertTrue(regex.containsMatchIn("xabcdy"))
|
|
||||||
assertTrue(regex.matches("abcd"))
|
|
||||||
assertFalse(regex matches "xabcdy")
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun givenCompletelyMatchingRegex_whenMatchResult_thenDestructuring() {
|
|
||||||
val regex = """a([bc]+)d?""".toRegex()
|
|
||||||
|
|
||||||
assertNull(regex.matchEntire("xabcdy"))
|
|
||||||
|
|
||||||
val matchResult = regex.matchEntire("abbccbbd")
|
|
||||||
|
|
||||||
assertNotNull(matchResult)
|
|
||||||
assertEquals(matchResult!!.value, matchResult.groupValues[0])
|
|
||||||
assertEquals(matchResult.destructured.toList(), matchResult.groupValues.drop(1))
|
|
||||||
assertEquals("bbccbb", matchResult.destructured.component1())
|
|
||||||
assertNull(matchResult.next())
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun givenPartiallyMatchingRegex_whenMatchResult_thenGroups() {
|
|
||||||
val regex = """a([bc]+)d?""".toRegex()
|
|
||||||
var matchResult = regex.find("abcb abbd")
|
|
||||||
|
|
||||||
assertNotNull(matchResult)
|
|
||||||
assertEquals(matchResult!!.value, matchResult.groupValues[0])
|
|
||||||
assertEquals("abcb", matchResult.value)
|
|
||||||
assertEquals(IntRange(0, 3), matchResult.range)
|
|
||||||
assertEquals(listOf("abcb", "bcb"), matchResult.groupValues)
|
|
||||||
assertEquals(matchResult.destructured.toList(), matchResult.groupValues.drop(1))
|
|
||||||
|
|
||||||
matchResult = matchResult.next()
|
|
||||||
|
|
||||||
assertNotNull(matchResult)
|
|
||||||
assertEquals("abbd", matchResult!!.value)
|
|
||||||
assertEquals("bb", matchResult.groupValues[1])
|
|
||||||
|
|
||||||
matchResult = matchResult.next()
|
|
||||||
|
|
||||||
assertNull(matchResult)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun givenPartiallyMatchingRegex_whenMatchResult_thenDestructuring() {
|
|
||||||
val regex = """([\w\s]+) is (\d+) years old""".toRegex()
|
|
||||||
val matchResult = regex.find("Mickey Mouse is 95 years old")
|
|
||||||
val (name, age) = matchResult!!.destructured
|
|
||||||
|
|
||||||
assertEquals("Mickey Mouse", name)
|
|
||||||
assertEquals("95", age)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun givenNonMatchingRegex_whenFindCalled_thenNull() {
|
|
||||||
val regex = """a([bc]+)d?""".toRegex()
|
|
||||||
val matchResult = regex.find("foo")
|
|
||||||
|
|
||||||
assertNull(matchResult)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun givenNonMatchingRegex_whenFindAllCalled_thenEmptySet() {
|
|
||||||
val regex = """a([bc]+)d?""".toRegex()
|
|
||||||
val matchResults = regex.findAll("foo")
|
|
||||||
|
|
||||||
assertNotNull(matchResults)
|
|
||||||
assertTrue(matchResults.none())
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun whenReplace_thenReplacement() {
|
|
||||||
val regex = """(red|green|blue)""".toRegex()
|
|
||||||
val beautiful = "Roses are red, Violets are blue"
|
|
||||||
val grim = regex.replace(beautiful, "dark")
|
|
||||||
val shiny = regex.replaceFirst(beautiful, "rainbow")
|
|
||||||
|
|
||||||
assertEquals("Roses are dark, Violets are dark", grim)
|
|
||||||
assertEquals("Roses are rainbow, Violets are blue", shiny)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun whenComplexReplace_thenReplacement() {
|
|
||||||
val regex = """(red|green|blue)""".toRegex()
|
|
||||||
val beautiful = "Roses are red, Violets are blue"
|
|
||||||
val reallyBeautiful = regex.replace(beautiful) {
|
|
||||||
matchResult -> matchResult.value.toUpperCase() + "!"
|
|
||||||
}
|
|
||||||
|
|
||||||
assertEquals("Roses are RED!, Violets are BLUE!", reallyBeautiful)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun whenSplit_thenList() {
|
|
||||||
val regex = """\W+""".toRegex()
|
|
||||||
val beautiful = "Roses are red, Violets are blue"
|
|
||||||
|
|
||||||
assertEquals(listOf("Roses", "are", "red", "Violets", "are", "blue"), regex.split(beautiful))
|
|
||||||
assertEquals(listOf("Roses", "are", "red", "Violets are blue"), regex.split(beautiful, 4))
|
|
||||||
assertEquals(regex.toPattern().split(beautiful).asList(), regex.split(beautiful))
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -1,8 +0,0 @@
|
|||||||
## Core Kotlin Annotations
|
|
||||||
|
|
||||||
This module contains articles about core Kotlin annotations.
|
|
||||||
|
|
||||||
### Relevant articles:
|
|
||||||
- [Kotlin Annotations](https://www.baeldung.com/kotlin-annotations)
|
|
||||||
- [Guide to Kotlin @JvmField](https://www.baeldung.com/kotlin-jvm-field-annotation)
|
|
||||||
- [Guide to JVM Platform Annotations in Kotlin](https://www.baeldung.com/kotlin-jvm-annotations)
|
|
@ -1,41 +0,0 @@
|
|||||||
<?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-kotlin-annotations</artifactId>
|
|
||||||
<name>core-kotlin-annotations</name>
|
|
||||||
<packaging>jar</packaging>
|
|
||||||
|
|
||||||
<parent>
|
|
||||||
<groupId>com.baeldung.core-kotlin-modules</groupId>
|
|
||||||
<artifactId>core-kotlin-modules</artifactId>
|
|
||||||
<version>1.0.0-SNAPSHOT</version>
|
|
||||||
</parent>
|
|
||||||
|
|
||||||
<dependencies>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.jetbrains.kotlin</groupId>
|
|
||||||
<artifactId>kotlin-stdlib-jdk8</artifactId>
|
|
||||||
<version>${kotlin.version}</version>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.assertj</groupId>
|
|
||||||
<artifactId>assertj-core</artifactId>
|
|
||||||
<version>${assertj.version}</version>
|
|
||||||
<scope>test</scope>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.jetbrains.kotlin</groupId>
|
|
||||||
<artifactId>kotlin-test</artifactId>
|
|
||||||
<version>${kotlin.version}</version>
|
|
||||||
<scope>test</scope>
|
|
||||||
</dependency>
|
|
||||||
</dependencies>
|
|
||||||
|
|
||||||
<properties>
|
|
||||||
<kotlin.version>1.3.30</kotlin.version>
|
|
||||||
<assertj.version>3.10.0</assertj.version>
|
|
||||||
</properties>
|
|
||||||
|
|
||||||
</project>
|
|
@ -1,7 +0,0 @@
|
|||||||
package com.baeldung.annotations
|
|
||||||
|
|
||||||
@Target(AnnotationTarget.FIELD)
|
|
||||||
annotation class Positive
|
|
||||||
|
|
||||||
@Target(AnnotationTarget.FIELD)
|
|
||||||
annotation class AllowedNames(val names: Array<String>)
|
|
@ -1,3 +0,0 @@
|
|||||||
package com.baeldung.annotations
|
|
||||||
|
|
||||||
class Item(@Positive val amount: Float, @AllowedNames(["Alice", "Bob"]) val name: String)
|
|
@ -1,7 +0,0 @@
|
|||||||
package com.baeldung.annotations
|
|
||||||
|
|
||||||
fun main(args: Array<String>) {
|
|
||||||
val item = Item(amount = 1.0f, name = "Bob")
|
|
||||||
val validator = Validator()
|
|
||||||
println("Is instance valid? ${validator.isValid(item)}")
|
|
||||||
}
|
|
@ -1,38 +0,0 @@
|
|||||||
package com.baeldung.annotations
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Naive annotation-based validator.
|
|
||||||
* @author A.Shcherbakov
|
|
||||||
*/
|
|
||||||
class Validator() {
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Return true if every item's property annotated with @Positive is positive and if
|
|
||||||
* every item's property annotated with @AllowedNames has a value specified in that annotation.
|
|
||||||
*/
|
|
||||||
fun isValid(item: Item): Boolean {
|
|
||||||
val fields = item::class.java.declaredFields
|
|
||||||
for (field in fields) {
|
|
||||||
field.isAccessible = true
|
|
||||||
for (annotation in field.annotations) {
|
|
||||||
val value = field.get(item)
|
|
||||||
if (field.isAnnotationPresent(Positive::class.java)) {
|
|
||||||
val amount = value as Float
|
|
||||||
if (amount < 0) {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (field.isAnnotationPresent(AllowedNames::class.java)) {
|
|
||||||
val allowedNames = field.getAnnotation(AllowedNames::class.java)?.names
|
|
||||||
val name = value as String
|
|
||||||
allowedNames?.let {
|
|
||||||
if (!it.contains(name)) {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,11 +0,0 @@
|
|||||||
package com.baeldung.jvmannotations
|
|
||||||
|
|
||||||
import java.util.*
|
|
||||||
|
|
||||||
interface Document {
|
|
||||||
|
|
||||||
@JvmDefault
|
|
||||||
fun getTypeDefault() = "document"
|
|
||||||
|
|
||||||
fun getType() = "document"
|
|
||||||
}
|
|
@ -1,9 +0,0 @@
|
|||||||
package com.baeldung.jvmannotations;
|
|
||||||
|
|
||||||
public class HtmlDocument implements Document {
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String getType() {
|
|
||||||
return "HTML";
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,66 +0,0 @@
|
|||||||
@file:JvmName("MessageHelper")
|
|
||||||
@file:JvmMultifileClass //used
|
|
||||||
package com.baeldung.jvmannotations
|
|
||||||
|
|
||||||
import java.util.*
|
|
||||||
|
|
||||||
@JvmName("getMyUsername")
|
|
||||||
fun getMyName() : String {
|
|
||||||
return "myUserId"
|
|
||||||
}
|
|
||||||
|
|
||||||
object MessageBroker {
|
|
||||||
@JvmStatic
|
|
||||||
var totalMessagesSent = 0
|
|
||||||
|
|
||||||
const val maxMessageLength = 0
|
|
||||||
|
|
||||||
@JvmStatic
|
|
||||||
fun clearAllMessages() {
|
|
||||||
}
|
|
||||||
|
|
||||||
@JvmStatic
|
|
||||||
@JvmOverloads
|
|
||||||
@Throws(Exception::class)
|
|
||||||
fun findMessages(sender : String, type : String = "text", maxResults : Int = 10) : List<Message> {
|
|
||||||
if(sender.isEmpty()) {
|
|
||||||
throw Exception()
|
|
||||||
}
|
|
||||||
return ArrayList()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
class Message {
|
|
||||||
|
|
||||||
// this would cause a compilation error since sender is immutable
|
|
||||||
// @set:JvmName("setSender")
|
|
||||||
val sender = "myself"
|
|
||||||
|
|
||||||
// this works as name is overridden
|
|
||||||
@JvmName("getSenderName")
|
|
||||||
fun getSender() : String = "from:$sender"
|
|
||||||
|
|
||||||
@get:JvmName("getReceiverName")
|
|
||||||
@set:JvmName("setReceiverName")
|
|
||||||
var receiver : String = ""
|
|
||||||
|
|
||||||
@get:JvmName("getContent")
|
|
||||||
@set:JvmName("setContent")
|
|
||||||
var text = ""
|
|
||||||
|
|
||||||
// generates a warning
|
|
||||||
@get:JvmName("getId")
|
|
||||||
private val id = 0
|
|
||||||
|
|
||||||
@get:JvmName("hasAttachment")
|
|
||||||
var hasAttachment = true
|
|
||||||
|
|
||||||
var isEncrypted = true
|
|
||||||
|
|
||||||
fun setReceivers(receiverNames : List<String>) {
|
|
||||||
}
|
|
||||||
|
|
||||||
@JvmName("setReceiverIds")
|
|
||||||
fun setReceivers(receiverNames : List<Int>) {
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,6 +0,0 @@
|
|||||||
@file:JvmMultifileClass
|
|
||||||
@file:JvmName("MessageHelper") //applies to all top level functions / variables / constants
|
|
||||||
package com.baeldung.jvmannotations
|
|
||||||
|
|
||||||
fun convert(message: Message) {
|
|
||||||
}
|
|
@ -1,16 +0,0 @@
|
|||||||
package com.baeldung.jvmannotations
|
|
||||||
|
|
||||||
import java.util.*
|
|
||||||
class TextDocument : Document {
|
|
||||||
override fun getType() = "text"
|
|
||||||
|
|
||||||
fun transformList(list : List<Number>) : List<Number> {
|
|
||||||
return list.filter { n -> n.toInt() > 1 }
|
|
||||||
}
|
|
||||||
|
|
||||||
fun transformListInverseWildcards(list : List<@JvmSuppressWildcards Number>) : List<@JvmWildcard Number> {
|
|
||||||
return list.filter { n -> n.toInt() > 1 }
|
|
||||||
}
|
|
||||||
|
|
||||||
var list : List<@JvmWildcard Any> = ArrayList()
|
|
||||||
}
|
|
@ -1,5 +0,0 @@
|
|||||||
package com.baeldung.jvmannotations
|
|
||||||
|
|
||||||
import java.util.*
|
|
||||||
|
|
||||||
class XmlDocument(d : Document) : Document by d
|
|
@ -1,12 +0,0 @@
|
|||||||
package com.baeldung.jvmfield
|
|
||||||
|
|
||||||
class JvmSample(text:String) {
|
|
||||||
@JvmField
|
|
||||||
val sampleText:String = text
|
|
||||||
}
|
|
||||||
|
|
||||||
class CompanionSample {
|
|
||||||
companion object {
|
|
||||||
@JvmField val MAX_LIMIT = 20
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,41 +0,0 @@
|
|||||||
package com.baeldung.annotations
|
|
||||||
|
|
||||||
import org.junit.Test
|
|
||||||
import kotlin.test.assertTrue
|
|
||||||
import kotlin.test.assertFalse
|
|
||||||
|
|
||||||
class ValidationTest {
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun whenAmountIsOneAndNameIsAlice_thenTrue() {
|
|
||||||
assertTrue(Validator().isValid(Item(1f, "Alice")))
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun whenAmountIsOneAndNameIsBob_thenTrue() {
|
|
||||||
assertTrue(Validator().isValid(Item(1f, "Bob")))
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun whenAmountIsMinusOneAndNameIsAlice_thenFalse() {
|
|
||||||
assertFalse(Validator().isValid(Item(-1f, "Alice")))
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun whenAmountIsMinusOneAndNameIsBob_thenFalse() {
|
|
||||||
assertFalse(Validator().isValid(Item(-1f, "Bob")))
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun whenAmountIsOneAndNameIsTom_thenFalse() {
|
|
||||||
assertFalse(Validator().isValid(Item(1f, "Tom")))
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun whenAmountIsMinusOneAndNameIsTom_thenFalse() {
|
|
||||||
assertFalse(Validator().isValid(Item(-1f, "Tom")))
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
}
|
|
@ -1,20 +0,0 @@
|
|||||||
package com.baeldung.range
|
|
||||||
|
|
||||||
import org.junit.Test
|
|
||||||
import kotlin.test.assertEquals
|
|
||||||
|
|
||||||
import com.baeldung.jvmannotations.*;
|
|
||||||
|
|
||||||
class DocumentTest {
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun testDefaultMethod() {
|
|
||||||
|
|
||||||
val myDocument = TextDocument()
|
|
||||||
val myTextDocument = XmlDocument(myDocument)
|
|
||||||
|
|
||||||
assertEquals("text", myDocument.getType())
|
|
||||||
assertEquals("text", myTextDocument.getType())
|
|
||||||
assertEquals("document", myTextDocument.getTypeDefault())
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,26 +0,0 @@
|
|||||||
package com.baeldung.jvmfield
|
|
||||||
|
|
||||||
import org.junit.Before
|
|
||||||
import org.junit.Test
|
|
||||||
import kotlin.test.assertTrue
|
|
||||||
|
|
||||||
class JvmSampleTest {
|
|
||||||
|
|
||||||
var sample = ""
|
|
||||||
|
|
||||||
@Before
|
|
||||||
fun setUp() {
|
|
||||||
sample = JvmSample("Hello!").sampleText
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun givenField_whenCheckValue_thenMatchesValue() {
|
|
||||||
assertTrue(sample == "Hello!")
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun givenStaticVariable_whenCheckValue_thenMatchesValue() {
|
|
||||||
// Sample when is treated as a static variable
|
|
||||||
assertTrue(CompanionSample.MAX_LIMIT == 20)
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,7 +0,0 @@
|
|||||||
## Core Kotlin Collections
|
|
||||||
|
|
||||||
This module contains articles about core Kotlin collections.
|
|
||||||
|
|
||||||
## Relevant articles:
|
|
||||||
|
|
||||||
- [Aggregate Operations in Kotlin](https://www.baeldung.com/kotlin/aggregate-operations)
|
|
@ -1,47 +0,0 @@
|
|||||||
<?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-kotlin-collections-2</artifactId>
|
|
||||||
<name>core-kotlin-collections-2</name>
|
|
||||||
<packaging>jar</packaging>
|
|
||||||
|
|
||||||
<parent>
|
|
||||||
<groupId>com.baeldung.core-kotlin-modules</groupId>
|
|
||||||
<artifactId>core-kotlin-modules</artifactId>
|
|
||||||
<version>1.0.0-SNAPSHOT</version>
|
|
||||||
</parent>
|
|
||||||
|
|
||||||
<dependencies>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.jetbrains.kotlin</groupId>
|
|
||||||
<artifactId>kotlin-stdlib-jdk8</artifactId>
|
|
||||||
<version>${kotlin.version}</version>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.apache.commons</groupId>
|
|
||||||
<artifactId>commons-math3</artifactId>
|
|
||||||
<version>${commons-math3.version}</version>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.assertj</groupId>
|
|
||||||
<artifactId>assertj-core</artifactId>
|
|
||||||
<version>${assertj.version}</version>
|
|
||||||
<scope>test</scope>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.jetbrains.kotlin</groupId>
|
|
||||||
<artifactId>kotlin-test</artifactId>
|
|
||||||
<version>${kotlin.version}</version>
|
|
||||||
<scope>test</scope>
|
|
||||||
</dependency>
|
|
||||||
</dependencies>
|
|
||||||
|
|
||||||
<properties>
|
|
||||||
<kotlin.version>1.3.30</kotlin.version>
|
|
||||||
<commons-math3.version>3.6.1</commons-math3.version>
|
|
||||||
<assertj.version>3.10.0</assertj.version>
|
|
||||||
</properties>
|
|
||||||
|
|
||||||
</project>
|
|
@ -1,107 +0,0 @@
|
|||||||
package com.baeldung.aggregate
|
|
||||||
|
|
||||||
class AggregateOperations {
|
|
||||||
private val numbers = listOf(1, 15, 3, 8)
|
|
||||||
|
|
||||||
fun countList(): Int {
|
|
||||||
return numbers.count()
|
|
||||||
}
|
|
||||||
|
|
||||||
fun sumList(): Int {
|
|
||||||
return numbers.sum()
|
|
||||||
}
|
|
||||||
|
|
||||||
fun averageList(): Double {
|
|
||||||
return numbers.average()
|
|
||||||
}
|
|
||||||
|
|
||||||
fun maximumInList(): Int? {
|
|
||||||
return numbers.max()
|
|
||||||
}
|
|
||||||
|
|
||||||
fun minimumInList(): Int? {
|
|
||||||
return numbers.min()
|
|
||||||
}
|
|
||||||
|
|
||||||
fun maximumByList(): Int? {
|
|
||||||
return numbers.maxBy { it % 5 }
|
|
||||||
}
|
|
||||||
|
|
||||||
fun minimumByList(): Int? {
|
|
||||||
return numbers.minBy { it % 5 }
|
|
||||||
}
|
|
||||||
|
|
||||||
fun maximumWithList(): String? {
|
|
||||||
val strings = listOf("Berlin", "Kolkata", "Prague", "Barcelona")
|
|
||||||
return strings.maxWith(compareBy { it.length % 4 })
|
|
||||||
}
|
|
||||||
|
|
||||||
fun minimumWithList(): String? {
|
|
||||||
val strings = listOf("Berlin", "Kolkata", "Prague", "Barcelona")
|
|
||||||
return strings.minWith(compareBy { it.length % 4 })
|
|
||||||
}
|
|
||||||
|
|
||||||
fun sumByList(): Int {
|
|
||||||
return numbers.sumBy { it * 5 }
|
|
||||||
}
|
|
||||||
|
|
||||||
fun sumByDoubleList(): Double {
|
|
||||||
return numbers.sumByDouble { it.toDouble() / 8 }
|
|
||||||
}
|
|
||||||
|
|
||||||
fun foldList(): Int {
|
|
||||||
return numbers.fold(100) { total, it ->
|
|
||||||
println("total = $total, it = $it")
|
|
||||||
total - it
|
|
||||||
} // ((((100 - 1)-15)-3)-8) = 73
|
|
||||||
}
|
|
||||||
|
|
||||||
fun foldRightList(): Int {
|
|
||||||
return numbers.foldRight(100) { it, total ->
|
|
||||||
println("total = $total, it = $it")
|
|
||||||
total - it
|
|
||||||
} // ((((100-8)-3)-15)-1) = 73
|
|
||||||
}
|
|
||||||
|
|
||||||
fun foldIndexedList(): Int {
|
|
||||||
return numbers.foldIndexed(100) { index, total, it ->
|
|
||||||
println("total = $total, it = $it, index = $index")
|
|
||||||
if (index.minus(2) >= 0) total - it else total
|
|
||||||
} // ((100 - 3)-8) = 89
|
|
||||||
}
|
|
||||||
|
|
||||||
fun foldRightIndexedList(): Int {
|
|
||||||
return numbers.foldRightIndexed(100) { index, it, total ->
|
|
||||||
println("total = $total, it = $it, index = $index")
|
|
||||||
if (index.minus(2) >= 0) total - it else total
|
|
||||||
} // ((100 - 8)-3) = 89
|
|
||||||
}
|
|
||||||
|
|
||||||
fun reduceList(): Int {
|
|
||||||
return numbers.reduce { total, it ->
|
|
||||||
println("total = $total, it = $it")
|
|
||||||
total - it
|
|
||||||
} // (((1 - 15)-3)-8) = -25
|
|
||||||
}
|
|
||||||
|
|
||||||
fun reduceRightList(): Int {
|
|
||||||
return numbers.reduceRight() { it, total ->
|
|
||||||
println("total = $total, it = $it")
|
|
||||||
total - it
|
|
||||||
} // ((8-3)-15)-1) = -11
|
|
||||||
}
|
|
||||||
|
|
||||||
fun reduceIndexedList(): Int {
|
|
||||||
return numbers.reduceIndexed { index, total, it ->
|
|
||||||
println("total = $total, it = $it, index = $index")
|
|
||||||
if (index.minus(2) >= 0) total - it else total
|
|
||||||
} // ((1-3)-8) = -10
|
|
||||||
}
|
|
||||||
|
|
||||||
fun reduceRightIndexedList(): Int {
|
|
||||||
return numbers.reduceRightIndexed { index, it, total ->
|
|
||||||
println("total = $total, it = $it, index = $index")
|
|
||||||
if (index.minus(2) >= 0) total - it else total
|
|
||||||
} // ((8-3) = 5
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,104 +0,0 @@
|
|||||||
package com.baeldung.aggregate
|
|
||||||
|
|
||||||
import org.junit.jupiter.api.Test
|
|
||||||
import kotlin.test.assertEquals
|
|
||||||
|
|
||||||
class AggregateOperationsUnitTest {
|
|
||||||
|
|
||||||
private val classUnderTest: AggregateOperations = AggregateOperations()
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun whenCountOfList_thenReturnsValue() {
|
|
||||||
assertEquals(4, classUnderTest.countList())
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun whenSumOfList_thenReturnsTotalValue() {
|
|
||||||
assertEquals(27, classUnderTest.sumList())
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun whenAverageOfList_thenReturnsValue() {
|
|
||||||
assertEquals(6.75, classUnderTest.averageList())
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun whenMaximumOfList_thenReturnsMaximumValue() {
|
|
||||||
assertEquals(15, classUnderTest.maximumInList())
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun whenMinimumOfList_thenReturnsMinimumValue() {
|
|
||||||
assertEquals(1, classUnderTest.minimumInList())
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun whenMaxByList_thenReturnsLargestValue() {
|
|
||||||
assertEquals(3, classUnderTest.maximumByList())
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun whenMinByList_thenReturnsSmallestValue() {
|
|
||||||
assertEquals(15, classUnderTest.minimumByList())
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun whenMaxWithList_thenReturnsLargestValue(){
|
|
||||||
assertEquals("Kolkata", classUnderTest.maximumWithList())
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun whenMinWithList_thenReturnsSmallestValue(){
|
|
||||||
assertEquals("Barcelona", classUnderTest.minimumWithList())
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun whenSumByList_thenReturnsIntegerValue(){
|
|
||||||
assertEquals(135, classUnderTest.sumByList())
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun whenSumByDoubleList_thenReturnsDoubleValue(){
|
|
||||||
assertEquals(3.375, classUnderTest.sumByDoubleList())
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun whenFoldList_thenReturnsValue(){
|
|
||||||
assertEquals(73, classUnderTest.foldList())
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun whenFoldRightList_thenReturnsValue(){
|
|
||||||
assertEquals(73, classUnderTest.foldRightList())
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun whenFoldIndexedList_thenReturnsValue(){
|
|
||||||
assertEquals(89, classUnderTest.foldIndexedList())
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun whenFoldRightIndexedList_thenReturnsValue(){
|
|
||||||
assertEquals(89, classUnderTest.foldRightIndexedList())
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun whenReduceList_thenReturnsValue(){
|
|
||||||
assertEquals(-25, classUnderTest.reduceList())
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun whenReduceRightList_thenReturnsValue(){
|
|
||||||
assertEquals(-11, classUnderTest.reduceRightList())
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun whenReduceIndexedList_thenReturnsValue(){
|
|
||||||
assertEquals(-10, classUnderTest.reduceIndexedList())
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun whenReduceRightIndexedList_thenReturnsValue(){
|
|
||||||
assertEquals(5, classUnderTest.reduceRightIndexedList())
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,16 +0,0 @@
|
|||||||
## Core Kotlin Collections
|
|
||||||
|
|
||||||
This module contains articles about core Kotlin collections.
|
|
||||||
|
|
||||||
### Relevant articles:
|
|
||||||
|
|
||||||
- [Split a List Into Parts in Kotlin](https://www.baeldung.com/kotlin-split-list-into-parts)
|
|
||||||
- [Finding an Element in a List Using Kotlin](https://www.baeldung.com/kotlin-finding-element-in-list)
|
|
||||||
- [Overview of Kotlin Collections API](https://www.baeldung.com/kotlin-collections-api)
|
|
||||||
- [Converting a List to Map in Kotlin](https://www.baeldung.com/kotlin-list-to-map)
|
|
||||||
- [Filtering Kotlin Collections](https://www.baeldung.com/kotlin-filter-collection)
|
|
||||||
- [Collection Transformations in Kotlin](https://www.baeldung.com/kotlin-collection-transformations)
|
|
||||||
- [Difference between fold and reduce in Kotlin](https://www.baeldung.com/kotlin/fold-vs-reduce)
|
|
||||||
- [Guide to Sorting in Kotlin](https://www.baeldung.com/kotlin-sort)
|
|
||||||
- [Working With Lists in Kotlin](https://www.baeldung.com/kotlin/lists)
|
|
||||||
- [Iterating Collections by Index in Kotlin](https://www.baeldung.com/kotlin/iterating-collections-by-index)
|
|
@ -1,47 +0,0 @@
|
|||||||
<?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-kotlin-collections</artifactId>
|
|
||||||
<name>core-kotlin-collections</name>
|
|
||||||
<packaging>jar</packaging>
|
|
||||||
|
|
||||||
<parent>
|
|
||||||
<groupId>com.baeldung.core-kotlin-modules</groupId>
|
|
||||||
<artifactId>core-kotlin-modules</artifactId>
|
|
||||||
<version>1.0.0-SNAPSHOT</version>
|
|
||||||
</parent>
|
|
||||||
|
|
||||||
<dependencies>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.jetbrains.kotlin</groupId>
|
|
||||||
<artifactId>kotlin-stdlib-jdk8</artifactId>
|
|
||||||
<version>${kotlin.version}</version>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.apache.commons</groupId>
|
|
||||||
<artifactId>commons-math3</artifactId>
|
|
||||||
<version>${commons-math3.version}</version>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.assertj</groupId>
|
|
||||||
<artifactId>assertj-core</artifactId>
|
|
||||||
<version>${assertj.version}</version>
|
|
||||||
<scope>test</scope>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.jetbrains.kotlin</groupId>
|
|
||||||
<artifactId>kotlin-test</artifactId>
|
|
||||||
<version>${kotlin.version}</version>
|
|
||||||
<scope>test</scope>
|
|
||||||
</dependency>
|
|
||||||
</dependencies>
|
|
||||||
|
|
||||||
<properties>
|
|
||||||
<kotlin.version>1.3.30</kotlin.version>
|
|
||||||
<commons-math3.version>3.6.1</commons-math3.version>
|
|
||||||
<assertj.version>3.10.0</assertj.version>
|
|
||||||
</properties>
|
|
||||||
|
|
||||||
</project>
|
|
@ -1,33 +0,0 @@
|
|||||||
package com.baeldung.index
|
|
||||||
|
|
||||||
fun main() {
|
|
||||||
|
|
||||||
// Index only
|
|
||||||
val colors = listOf("Red", "Green", "Blue")
|
|
||||||
for (i in colors.indices) {
|
|
||||||
println(colors[i])
|
|
||||||
}
|
|
||||||
|
|
||||||
val colorArray = arrayOf("Red", "Green", "Blue")
|
|
||||||
for (i in colorArray.indices) {
|
|
||||||
println(colorArray[i])
|
|
||||||
}
|
|
||||||
|
|
||||||
(0 until colors.size).forEach { println(colors[it]) }
|
|
||||||
for (i in 0 until colors.size) {
|
|
||||||
println(colors[i])
|
|
||||||
}
|
|
||||||
|
|
||||||
// Index and Value
|
|
||||||
colors.forEachIndexed { i, v -> println("The value for index $i is $v") }
|
|
||||||
for (indexedValue in colors.withIndex()) {
|
|
||||||
println("The value for index ${indexedValue.index} is ${indexedValue.value}")
|
|
||||||
}
|
|
||||||
|
|
||||||
for ((i, v) in colors.withIndex()) {
|
|
||||||
println("The value for index $i is $v")
|
|
||||||
}
|
|
||||||
|
|
||||||
colors.filterIndexed { i, _ -> i % 2 == 0 }
|
|
||||||
colors.filterIndexed { _, v -> v == "RED" }
|
|
||||||
}
|
|
@ -1,204 +0,0 @@
|
|||||||
package com.baeldung.kotlin.collections
|
|
||||||
|
|
||||||
import kotlin.collections.List
|
|
||||||
|
|
||||||
class ListExample {
|
|
||||||
|
|
||||||
private val countries = listOf("Germany", "India", "Japan", "Brazil", "Australia")
|
|
||||||
private val cities = mutableListOf("Berlin", "Calcutta", "Seoul", "Sao Paulo", "Sydney")
|
|
||||||
|
|
||||||
fun createList(): List<String> {
|
|
||||||
val countryList = listOf("Germany", "India", "Japan", "Brazil")
|
|
||||||
return countryList
|
|
||||||
}
|
|
||||||
|
|
||||||
fun createMutableList(): MutableList<String> {
|
|
||||||
val cityList = mutableListOf("Berlin", "Calcutta", "Seoul", "Sao Paulo")
|
|
||||||
return cityList
|
|
||||||
}
|
|
||||||
|
|
||||||
fun iterateUsingForEachLoop(): List<Int> {
|
|
||||||
val countryLength = mutableListOf<Int>()
|
|
||||||
countries.forEach { it ->
|
|
||||||
print("$it ")
|
|
||||||
println(" Length: ${it.length}")
|
|
||||||
countryLength.add(it.length)
|
|
||||||
}
|
|
||||||
return countryLength
|
|
||||||
}
|
|
||||||
|
|
||||||
fun iterateUsingForLoop(): List<Int> {
|
|
||||||
val countryLength = mutableListOf<Int>()
|
|
||||||
for (country in countries) {
|
|
||||||
print("$country ")
|
|
||||||
println(" Length: ${country.length}")
|
|
||||||
countryLength.add(country.length)
|
|
||||||
}
|
|
||||||
return countryLength
|
|
||||||
}
|
|
||||||
|
|
||||||
fun iterateUsingForLoopRange(): List<Int> {
|
|
||||||
val countryLength = mutableListOf<Int>()
|
|
||||||
for (i in 0 until countries.size) {
|
|
||||||
print("${countries[i]} ")
|
|
||||||
println(" Length: ${countries[i].length}")
|
|
||||||
countryLength.add(countries[i].length)
|
|
||||||
}
|
|
||||||
return countryLength
|
|
||||||
}
|
|
||||||
|
|
||||||
fun iterateUsingForEachIndexedLoop(): List<Int> {
|
|
||||||
val countryLength = mutableListOf<Int>()
|
|
||||||
countries.forEachIndexed { i, e ->
|
|
||||||
println("country[$i] = $e")
|
|
||||||
print(" Index: $i")
|
|
||||||
println(" Length: ${e.length}")
|
|
||||||
countryLength.add(e.length)
|
|
||||||
}
|
|
||||||
return countryLength
|
|
||||||
}
|
|
||||||
|
|
||||||
fun iterateUsingListIterator() {
|
|
||||||
val iterator = countries.listIterator()
|
|
||||||
while (iterator.hasNext()) {
|
|
||||||
val country = iterator.next()
|
|
||||||
print("$country ")
|
|
||||||
}
|
|
||||||
println()
|
|
||||||
|
|
||||||
while (iterator.hasPrevious()) {
|
|
||||||
println("Index: ${iterator.previousIndex()}")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun iterateUsingIterator() {
|
|
||||||
val iterator = cities.iterator()
|
|
||||||
iterator.next()
|
|
||||||
iterator.remove()
|
|
||||||
println(cities)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun iterateUsingMutableListIterator() {
|
|
||||||
val iterator = cities.listIterator(1)
|
|
||||||
iterator.next()
|
|
||||||
iterator.add("London")
|
|
||||||
iterator.next()
|
|
||||||
iterator.set("Milan")
|
|
||||||
println(cities)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun retrieveElementsInList(): String {
|
|
||||||
println(countries[2])
|
|
||||||
return countries[2]
|
|
||||||
}
|
|
||||||
|
|
||||||
fun retrieveElementsUsingGet(): String {
|
|
||||||
println(countries.get(3))
|
|
||||||
return countries.get(3)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun retrieveElementsFirstAndLast(): String? {
|
|
||||||
println(countries.first())
|
|
||||||
println(countries.last())
|
|
||||||
println(countries.first { it.length > 7 })
|
|
||||||
println(countries.last { it.startsWith("J") })
|
|
||||||
println(countries.firstOrNull { it.length > 8 })
|
|
||||||
return countries.firstOrNull { it.length > 8 }
|
|
||||||
}
|
|
||||||
|
|
||||||
fun retrieveSubList(): List<String> {
|
|
||||||
val subList = countries.subList(1, 4)
|
|
||||||
println(subList)
|
|
||||||
return subList
|
|
||||||
}
|
|
||||||
|
|
||||||
fun retrieveListSliceUsingIndices(): List<String> {
|
|
||||||
val sliceList = countries.slice(1..4)
|
|
||||||
println(sliceList)
|
|
||||||
return sliceList
|
|
||||||
}
|
|
||||||
|
|
||||||
fun retrieveListSliceUsingIndicesList(): List<String> {
|
|
||||||
val sliceList = countries.slice(listOf(1, 4))
|
|
||||||
println(sliceList)
|
|
||||||
return sliceList
|
|
||||||
}
|
|
||||||
|
|
||||||
fun countList(): Int {
|
|
||||||
val count = countries.count()
|
|
||||||
println(count)
|
|
||||||
return count
|
|
||||||
}
|
|
||||||
|
|
||||||
fun countListUsingPredicate(): Int {
|
|
||||||
val count = countries.count { it.length > 5 }
|
|
||||||
println(count)
|
|
||||||
return count
|
|
||||||
}
|
|
||||||
|
|
||||||
fun countListUsingProperty(): Int {
|
|
||||||
val size = countries.size
|
|
||||||
println(size)
|
|
||||||
return size
|
|
||||||
}
|
|
||||||
|
|
||||||
fun addToList(): List<String> {
|
|
||||||
cities.add("Barcelona")
|
|
||||||
println(cities)
|
|
||||||
cities.add(3, "London")
|
|
||||||
println(cities)
|
|
||||||
cities.addAll(listOf("Singapore", "Moscow"))
|
|
||||||
println(cities)
|
|
||||||
cities.addAll(2, listOf("Prague", "Amsterdam"))
|
|
||||||
println(cities)
|
|
||||||
return cities
|
|
||||||
}
|
|
||||||
|
|
||||||
fun removeFromList(): List<String> {
|
|
||||||
cities.remove("Seoul")
|
|
||||||
println(cities)
|
|
||||||
cities.removeAt(1)
|
|
||||||
println(cities)
|
|
||||||
return cities
|
|
||||||
}
|
|
||||||
|
|
||||||
fun replaceFromList(): List<String> {
|
|
||||||
cities.set(3, "Prague")
|
|
||||||
println(cities)
|
|
||||||
cities[4] = "Moscow"
|
|
||||||
println(cities)
|
|
||||||
cities.fill("Barcelona")
|
|
||||||
println(cities)
|
|
||||||
return cities
|
|
||||||
}
|
|
||||||
|
|
||||||
fun sortMutableList(): List<String> {
|
|
||||||
cities.sort()
|
|
||||||
println(cities)
|
|
||||||
cities.sortDescending()
|
|
||||||
println(cities)
|
|
||||||
return cities
|
|
||||||
}
|
|
||||||
|
|
||||||
fun sortList(): List<String> {
|
|
||||||
val sortedCountries = countries.sorted()
|
|
||||||
println("countries = $countries")
|
|
||||||
println("sortedCountries = $sortedCountries")
|
|
||||||
val sortedCountriesDescending = countries.sortedDescending()
|
|
||||||
println("countries = $countries")
|
|
||||||
println("sortedCountriesDescending = $sortedCountriesDescending")
|
|
||||||
return sortedCountriesDescending
|
|
||||||
}
|
|
||||||
|
|
||||||
fun checkOneElementInList(): Boolean {
|
|
||||||
return countries.contains("Germany")
|
|
||||||
}
|
|
||||||
|
|
||||||
fun checkOneElementInListUsingOperator(): Boolean {
|
|
||||||
return "Spain" in countries
|
|
||||||
}
|
|
||||||
|
|
||||||
fun checkElementsInList(): Boolean {
|
|
||||||
return cities.containsAll(listOf("Calcutta", "Sao Paulo", "Sydney"))
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,42 +0,0 @@
|
|||||||
package com.baeldung.sorting
|
|
||||||
|
|
||||||
fun sortMethodUsage() {
|
|
||||||
val sortedValues = mutableListOf(1, 2, 7, 6, 5, 6)
|
|
||||||
sortedValues.sort()
|
|
||||||
println(sortedValues)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun sortByMethodUsage() {
|
|
||||||
val sortedValues = mutableListOf(1 to "a", 2 to "b", 7 to "c", 6 to "d", 5 to "c", 6 to "e")
|
|
||||||
sortedValues.sortBy { it.second }
|
|
||||||
println(sortedValues)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun sortWithMethodUsage() {
|
|
||||||
val sortedValues = mutableListOf(1 to "a", 2 to "b", 7 to "c", 6 to "d", 5 to "c", 6 to "e")
|
|
||||||
sortedValues.sortWith(compareBy({it.second}, {it.first}))
|
|
||||||
println(sortedValues)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun <T : kotlin.Comparable<T>> getSimpleComparator() : Comparator<T> {
|
|
||||||
val ascComparator = naturalOrder<T>()
|
|
||||||
return ascComparator
|
|
||||||
}
|
|
||||||
|
|
||||||
fun getComplexComparator() {
|
|
||||||
val complexComparator = compareBy<Pair<Int, String>>({it.first}, {it.second})
|
|
||||||
}
|
|
||||||
|
|
||||||
fun nullHandlingUsage() {
|
|
||||||
val sortedValues = mutableListOf(1 to "a", 2 to null, 7 to "c", 6 to "d", 5 to "c", 6 to "e")
|
|
||||||
sortedValues.sortWith(nullsLast(compareBy { it.second }))
|
|
||||||
println(sortedValues)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun extendedComparatorUsage() {
|
|
||||||
val students = mutableListOf(21 to "Helen", 21 to "Tom", 20 to "Jim")
|
|
||||||
|
|
||||||
val ageComparator = compareBy<Pair<Int, String?>> {it.first}
|
|
||||||
val ageAndNameComparator = ageComparator.thenByDescending {it.second}
|
|
||||||
println(students.sortedWith(ageAndNameComparator))
|
|
||||||
}
|
|
@ -1,212 +0,0 @@
|
|||||||
package com.baeldung.collections
|
|
||||||
|
|
||||||
import org.assertj.core.api.Assertions.assertThat
|
|
||||||
import org.junit.Test
|
|
||||||
import kotlin.test.assertEquals
|
|
||||||
import kotlin.test.assertFalse
|
|
||||||
import kotlin.test.assertTrue
|
|
||||||
|
|
||||||
class CollectionsTest {
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun whenUseDifferentCollections_thenSuccess() {
|
|
||||||
val theList = listOf("one", "two", "three")
|
|
||||||
assertTrue(theList.contains("two"))
|
|
||||||
|
|
||||||
val theMutableList = mutableListOf("one", "two", "three")
|
|
||||||
theMutableList.add("four")
|
|
||||||
assertTrue(theMutableList.contains("four"))
|
|
||||||
|
|
||||||
val theSet = setOf("one", "two", "three")
|
|
||||||
assertTrue(theSet.contains("three"))
|
|
||||||
|
|
||||||
val theMutableSet = mutableSetOf("one", "two", "three")
|
|
||||||
theMutableSet.add("four")
|
|
||||||
assertTrue(theMutableSet.contains("four"))
|
|
||||||
|
|
||||||
val theMap = mapOf(1 to "one", 2 to "two", 3 to "three")
|
|
||||||
assertEquals(theMap[2], "two")
|
|
||||||
|
|
||||||
val theMutableMap = mutableMapOf(1 to "one", 2 to "two", 3 to "three")
|
|
||||||
theMutableMap[4] = "four"
|
|
||||||
assertEquals(theMutableMap[4], "four")
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun whenSliceCollection_thenSuccess() {
|
|
||||||
val theList = listOf("one", "two", "three")
|
|
||||||
val resultList = theList.slice(1..2)
|
|
||||||
|
|
||||||
assertEquals(2, resultList.size)
|
|
||||||
assertTrue(resultList.contains("two"))
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun whenJoinTwoCollections_thenSuccess() {
|
|
||||||
val firstList = listOf("one", "two", "three")
|
|
||||||
val secondList = listOf("four", "five", "six")
|
|
||||||
val resultList = firstList + secondList
|
|
||||||
|
|
||||||
assertEquals(6, resultList.size)
|
|
||||||
assertTrue(resultList.contains("two"))
|
|
||||||
assertTrue(resultList.contains("five"))
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun whenFilterNullValues_thenSuccess() {
|
|
||||||
val theList = listOf("one", null, "two", null, "three")
|
|
||||||
val resultList = theList.filterNotNull()
|
|
||||||
|
|
||||||
assertEquals(3, resultList.size)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun whenFilterNonPositiveValues_thenSuccess() {
|
|
||||||
val theList = listOf(1, 2, -3, -4, 5, -6)
|
|
||||||
val resultList = theList.filter { it > 0 }
|
|
||||||
//val resultList = theList.filter{ x -> x > 0}
|
|
||||||
|
|
||||||
assertEquals(3, resultList.size)
|
|
||||||
assertTrue(resultList.contains(1))
|
|
||||||
assertFalse(resultList.contains(-4))
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun whenDropFirstItems_thenRemoved() {
|
|
||||||
val theList = listOf("one", "two", "three", "four")
|
|
||||||
val resultList = theList.drop(2)
|
|
||||||
|
|
||||||
assertEquals(2, resultList.size)
|
|
||||||
assertFalse(resultList.contains("one"))
|
|
||||||
assertFalse(resultList.contains("two"))
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun whenDropFirstItemsBasedOnCondition_thenRemoved() {
|
|
||||||
val theList = listOf("one", "two", "three", "four")
|
|
||||||
val resultList = theList.dropWhile { it.length < 4 }
|
|
||||||
|
|
||||||
assertEquals(2, resultList.size)
|
|
||||||
assertFalse(resultList.contains("one"))
|
|
||||||
assertFalse(resultList.contains("two"))
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun whenExcludeItems_thenRemoved() {
|
|
||||||
val firstList = listOf("one", "two", "three")
|
|
||||||
val secondList = listOf("one", "three")
|
|
||||||
val resultList = firstList - secondList
|
|
||||||
|
|
||||||
assertEquals(1, resultList.size)
|
|
||||||
assertTrue(resultList.contains("two"))
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun whenSearchForExistingItem_thenFound() {
|
|
||||||
val theList = listOf("one", "two", "three")
|
|
||||||
|
|
||||||
assertTrue("two" in theList)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun whenGroupItems_thenSuccess() {
|
|
||||||
val theList = listOf(1, 2, 3, 4, 5, 6)
|
|
||||||
val resultMap = theList.groupBy { it % 3 }
|
|
||||||
|
|
||||||
assertEquals(3, resultMap.size)
|
|
||||||
print(resultMap[1])
|
|
||||||
assertTrue(resultMap[1]!!.contains(1))
|
|
||||||
assertTrue(resultMap[2]!!.contains(5))
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun whenApplyFunctionToAllItems_thenSuccess() {
|
|
||||||
val theList = listOf(1, 2, 3, 4, 5, 6)
|
|
||||||
val resultList = theList.map { it * it }
|
|
||||||
print(resultList)
|
|
||||||
assertEquals(4, resultList[1])
|
|
||||||
assertEquals(9, resultList[2])
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun whenApplyMultiOutputFunctionToAllItems_thenSuccess() {
|
|
||||||
val theList = listOf("John", "Tom")
|
|
||||||
val resultList = theList.flatMap { it.toLowerCase().toList() }
|
|
||||||
print(resultList)
|
|
||||||
assertEquals(7, resultList.size)
|
|
||||||
assertTrue(resultList.contains('j'))
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun whenApplyFunctionToAllItemsWithStartingValue_thenSuccess() {
|
|
||||||
val theList = listOf(1, 2, 3, 4, 5, 6)
|
|
||||||
val finalResult = theList.fold(1000, { oldResult, currentItem -> oldResult + (currentItem * currentItem) })
|
|
||||||
print(finalResult)
|
|
||||||
assertEquals(1091, finalResult)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun whenApplyingChunked_thenShouldBreakTheCollection() {
|
|
||||||
val theList = listOf(1, 2, 3, 4, 5)
|
|
||||||
val chunked = theList.chunked(2)
|
|
||||||
|
|
||||||
assertThat(chunked.size).isEqualTo(3)
|
|
||||||
assertThat(chunked.first()).contains(1, 2)
|
|
||||||
assertThat(chunked[1]).contains(3, 4)
|
|
||||||
assertThat(chunked.last()).contains(5)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun whenApplyingChunkedWithTransformation_thenShouldBreakTheCollection() {
|
|
||||||
val theList = listOf(1, 2, 3, 4, 5)
|
|
||||||
val chunked = theList.chunked(3) { it.joinToString(", ") }
|
|
||||||
|
|
||||||
assertThat(chunked.size).isEqualTo(2)
|
|
||||||
assertThat(chunked.first()).isEqualTo("1, 2, 3")
|
|
||||||
assertThat(chunked.last()).isEqualTo("4, 5")
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun whenApplyingWindowed_thenShouldCreateSlidingWindowsOfElements() {
|
|
||||||
val theList = (1..6).toList()
|
|
||||||
val windowed = theList.windowed(3)
|
|
||||||
|
|
||||||
assertThat(windowed.size).isEqualTo(4)
|
|
||||||
assertThat(windowed.first()).contains(1, 2, 3)
|
|
||||||
assertThat(windowed[1]).contains(2, 3, 4)
|
|
||||||
assertThat(windowed[2]).contains(3, 4, 5)
|
|
||||||
assertThat(windowed.last()).contains(4, 5, 6)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun whenApplyingWindowedWithTwoSteps_thenShouldCreateSlidingWindowsOfElements() {
|
|
||||||
val theList = (1..6).toList()
|
|
||||||
val windowed = theList.windowed(size = 3, step = 2)
|
|
||||||
|
|
||||||
assertThat(windowed.size).isEqualTo(2)
|
|
||||||
assertThat(windowed.first()).contains(1, 2, 3)
|
|
||||||
assertThat(windowed.last()).contains(3, 4, 5)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun whenApplyingPartialWindowedWithTwoSteps_thenShouldCreateSlidingWindowsOfElements() {
|
|
||||||
val theList = (1..6).toList()
|
|
||||||
val windowed = theList.windowed(size = 3, step = 2, partialWindows = true)
|
|
||||||
|
|
||||||
assertThat(windowed.size).isEqualTo(3)
|
|
||||||
assertThat(windowed.first()).contains(1, 2, 3)
|
|
||||||
assertThat(windowed[1]).contains(3, 4, 5)
|
|
||||||
assertThat(windowed.last()).contains(5, 6)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun whenApplyingTransformingWindows_thenShouldCreateSlidingWindowsOfElements() {
|
|
||||||
val theList = (1..6).toList()
|
|
||||||
val windowed = theList.windowed(size = 3, step = 2, partialWindows = true) { it.joinToString(", ") }
|
|
||||||
|
|
||||||
assertThat(windowed.size).isEqualTo(3)
|
|
||||||
assertThat(windowed.first()).isEqualTo("1, 2, 3")
|
|
||||||
assertThat(windowed[1]).isEqualTo("3, 4, 5")
|
|
||||||
assertThat(windowed.last()).isEqualTo("5, 6")
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,48 +0,0 @@
|
|||||||
package com.baeldung.collections.transformations
|
|
||||||
|
|
||||||
import org.junit.Assert.assertEquals
|
|
||||||
import org.junit.Test
|
|
||||||
|
|
||||||
class AssociateUnitTest {
|
|
||||||
@Test
|
|
||||||
fun testToMap() {
|
|
||||||
val input = listOf(Pair("one", 1), Pair("two", 2))
|
|
||||||
val map = input.toMap()
|
|
||||||
assertEquals(mapOf("one" to 1, "two" to 2), map)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun testAssociateWith() {
|
|
||||||
val inputs = listOf("Hi", "there")
|
|
||||||
val map = inputs.associateWith { k -> k.length }
|
|
||||||
assertEquals(mapOf("Hi" to 2, "there" to 5), map)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun testAssociateBy() {
|
|
||||||
val inputs = listOf("Hi", "there")
|
|
||||||
val map = inputs.associateBy { v -> v.length }
|
|
||||||
assertEquals(mapOf(2 to "Hi", 5 to "there"), map)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun testAssociate() {
|
|
||||||
val inputs = listOf("Hi", "there")
|
|
||||||
val map = inputs.associate { e -> Pair(e.toUpperCase(), e.reversed()) }
|
|
||||||
assertEquals(mapOf("HI" to "iH", "THERE" to "ereht"), map)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun testAssociateByDuplicateKeys() {
|
|
||||||
val inputs = listOf("one", "two")
|
|
||||||
val map = inputs.associateBy { v -> v.length }
|
|
||||||
assertEquals(mapOf(3 to "two"), map)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun testGroupBy() {
|
|
||||||
val inputs = listOf("one", "two", "three")
|
|
||||||
val map = inputs.groupBy { v -> v.length }
|
|
||||||
assertEquals(mapOf(3 to listOf("one", "two"), 5 to listOf("three")), map)
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,43 +0,0 @@
|
|||||||
package com.baeldung.collections.transformations
|
|
||||||
|
|
||||||
import org.junit.Assert.assertEquals
|
|
||||||
import org.junit.Test
|
|
||||||
|
|
||||||
class FilterUnitTest {
|
|
||||||
@Test
|
|
||||||
fun testFilterWithLambda() {
|
|
||||||
val input = listOf(1, 2, 3, 4, 5)
|
|
||||||
val filtered = input.filter { it <= 3 }
|
|
||||||
assertEquals(listOf(1, 2, 3), filtered)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun testFilterWithMethodReference() {
|
|
||||||
val input = listOf(1, 2, 3, 4, 5)
|
|
||||||
val filtered = input.filter(this::isSmall)
|
|
||||||
assertEquals(listOf(1, 2, 3), filtered)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun testFilterNotWithMethodReference() {
|
|
||||||
val input = listOf(1, 2, 3, 4, 5)
|
|
||||||
val filtered = input.filterNot(this::isSmall)
|
|
||||||
assertEquals(listOf(4, 5), filtered)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun testFilterIndexed() {
|
|
||||||
val input = listOf(5, 4, 3, 2, 1)
|
|
||||||
val filtered = input.filterIndexed { index, element -> index < 3 }
|
|
||||||
assertEquals(listOf(5, 4, 3), filtered)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun testFilterNotNull() {
|
|
||||||
val nullable: List<String?> = listOf("Hello", null, "World")
|
|
||||||
val nonnull: List<String> = nullable.filterNotNull()
|
|
||||||
assertEquals(listOf("Hello", "World"), nonnull)
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun isSmall(i: Int) = i <= 3
|
|
||||||
}
|
|
@ -1,21 +0,0 @@
|
|||||||
package com.baeldung.collections.transformations
|
|
||||||
|
|
||||||
import org.junit.Assert.assertEquals
|
|
||||||
import org.junit.Test
|
|
||||||
|
|
||||||
class FlattenUnitTest {
|
|
||||||
@Test
|
|
||||||
fun testFlatten() {
|
|
||||||
val inputs = listOf("one", "two", "three")
|
|
||||||
val characters = inputs.map(String::toList)
|
|
||||||
val flattened = characters.flatten();
|
|
||||||
assertEquals(listOf('o', 'n', 'e', 't', 'w', 'o', 't', 'h', 'r', 'e', 'e'), flattened)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun testFlatMap() {
|
|
||||||
val inputs = listOf("one", "two", "three")
|
|
||||||
val characters = inputs.flatMap(String::toList)
|
|
||||||
assertEquals(listOf('o', 'n', 'e', 't', 'w', 'o', 't', 'h', 'r', 'e', 'e'), characters)
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,46 +0,0 @@
|
|||||||
package com.baeldung.collections.transformations
|
|
||||||
|
|
||||||
import org.junit.Assert.assertEquals
|
|
||||||
import org.junit.Test
|
|
||||||
|
|
||||||
class JoinToUnitTest {
|
|
||||||
@Test
|
|
||||||
fun testJoinToString() {
|
|
||||||
val inputs = listOf("Jan", "Feb", "Mar", "Apr", "May")
|
|
||||||
|
|
||||||
val simpleString = inputs.joinToString()
|
|
||||||
assertEquals("Jan, Feb, Mar, Apr, May", simpleString)
|
|
||||||
|
|
||||||
val detailedString = inputs.joinToString(separator = ",", prefix="Months: ", postfix=".")
|
|
||||||
assertEquals("Months: Jan,Feb,Mar,Apr,May.", detailedString)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun testJoinToStringLimits() {
|
|
||||||
val inputs = listOf("Jan", "Feb", "Mar", "Apr", "May")
|
|
||||||
|
|
||||||
val simpleString = inputs.joinToString(limit = 3)
|
|
||||||
assertEquals("Jan, Feb, Mar, ...", simpleString)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun testJoinToStringTransform() {
|
|
||||||
val inputs = listOf("Jan", "Feb", "Mar", "Apr", "May")
|
|
||||||
|
|
||||||
val simpleString = inputs.joinToString(transform = String::toUpperCase)
|
|
||||||
assertEquals("JAN, FEB, MAR, APR, MAY", simpleString)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun testJoinTo() {
|
|
||||||
val inputs = listOf("Jan", "Feb", "Mar", "Apr", "May")
|
|
||||||
|
|
||||||
val output = StringBuilder()
|
|
||||||
output.append("My ")
|
|
||||||
.append(inputs.size)
|
|
||||||
.append(" elements: ")
|
|
||||||
inputs.joinTo(output)
|
|
||||||
|
|
||||||
assertEquals("My 5 elements: Jan, Feb, Mar, Apr, May", output.toString())
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,53 +0,0 @@
|
|||||||
package com.baeldung.collections.transformations
|
|
||||||
|
|
||||||
import org.junit.Assert.assertEquals
|
|
||||||
import org.junit.Test
|
|
||||||
|
|
||||||
class MapUnitTest {
|
|
||||||
@Test
|
|
||||||
fun testMapWithLambda() {
|
|
||||||
val input = listOf("one", "two", "three")
|
|
||||||
|
|
||||||
val reversed = input.map { it.reversed() }
|
|
||||||
assertEquals(listOf("eno", "owt", "eerht"), reversed)
|
|
||||||
|
|
||||||
val lengths = input.map { it.length }
|
|
||||||
assertEquals(listOf(3, 3, 5), lengths)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun testMapIndexed() {
|
|
||||||
val input = listOf(3, 2, 1)
|
|
||||||
val result = input.mapIndexed { index, value -> index * value }
|
|
||||||
assertEquals(listOf(0, 2, 2), result)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun testMapNotNull() {
|
|
||||||
val input = listOf(1, 2, 3, 4, 5)
|
|
||||||
val smallSquares = input.mapNotNull {
|
|
||||||
if (it <= 3) {
|
|
||||||
it * it
|
|
||||||
} else {
|
|
||||||
null
|
|
||||||
}
|
|
||||||
}
|
|
||||||
assertEquals(listOf(1, 4, 9), smallSquares)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun mapMapKeys() {
|
|
||||||
val inputs = mapOf("one" to 1, "two" to 2, "three" to 3)
|
|
||||||
|
|
||||||
val uppercases = inputs.mapKeys { it.key.toUpperCase() }
|
|
||||||
assertEquals(mapOf("ONE" to 1, "TWO" to 2, "THREE" to 3), uppercases)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun mapMapValues() {
|
|
||||||
val inputs = mapOf("one" to 1, "two" to 2, "three" to 3)
|
|
||||||
|
|
||||||
val squares = inputs.mapValues { it.value * it.value }
|
|
||||||
assertEquals(mapOf("one" to 1, "two" to 4, "three" to 9), squares)
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,22 +0,0 @@
|
|||||||
package com.baeldung.collections.transformations
|
|
||||||
|
|
||||||
import org.junit.Assert.assertEquals
|
|
||||||
import org.junit.Test
|
|
||||||
|
|
||||||
class ReduceUnitTest {
|
|
||||||
@Test
|
|
||||||
fun testJoinToStringAsReduce() {
|
|
||||||
val inputs = listOf("Jan", "Feb", "Mar", "Apr", "May")
|
|
||||||
|
|
||||||
val result = inputs.reduce { acc, next -> "$acc, $next" }
|
|
||||||
assertEquals("Jan, Feb, Mar, Apr, May", result)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun testFoldToLength() {
|
|
||||||
val inputs = listOf("Jan", "Feb", "Mar", "Apr", "May")
|
|
||||||
|
|
||||||
val result = inputs.fold(0) { acc, next -> acc + next.length }
|
|
||||||
assertEquals(15, result)
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,34 +0,0 @@
|
|||||||
package com.baeldung.collections.transformations
|
|
||||||
|
|
||||||
import org.junit.Assert.assertEquals
|
|
||||||
import org.junit.Test
|
|
||||||
|
|
||||||
class ZipUnitTest {
|
|
||||||
@Test
|
|
||||||
fun testZip() {
|
|
||||||
val left = listOf("one", "two", "three")
|
|
||||||
val right = listOf(1, 2, 3)
|
|
||||||
val zipped = left.zip(right)
|
|
||||||
assertEquals (listOf(Pair("one", 1), Pair("two", 2), Pair("three", 3)), zipped)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun testZipShort() {
|
|
||||||
val left = listOf("one", "two")
|
|
||||||
val right = listOf(1, 2, 3)
|
|
||||||
val zipped = left.zip(right)
|
|
||||||
assertEquals (listOf(Pair("one", 1), Pair("two", 2)), zipped)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun testUnzip() {
|
|
||||||
val left = listOf("one", "two", "three")
|
|
||||||
val right = listOf(1, 2, 3)
|
|
||||||
val zipped = left.zip(right)
|
|
||||||
|
|
||||||
val (newLeft, newRight) = zipped.unzip()
|
|
||||||
assertEquals(left, newLeft)
|
|
||||||
assertEquals(right, newRight)
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -1,39 +0,0 @@
|
|||||||
package com.baeldung.filter
|
|
||||||
|
|
||||||
import org.junit.jupiter.api.Assertions.assertIterableEquals
|
|
||||||
import org.junit.jupiter.api.Test
|
|
||||||
|
|
||||||
internal class ChunkedTest {
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun givenDNAFragmentString_whenChunking_thenProduceListOfChunks() {
|
|
||||||
val dnaFragment = "ATTCGCGGCCGCCAA"
|
|
||||||
|
|
||||||
val fragments = dnaFragment.chunked(3)
|
|
||||||
|
|
||||||
assertIterableEquals(listOf("ATT", "CGC", "GGC", "CGC", "CAA"), fragments)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun givenDNAString_whenChunkingWithTransformer_thenProduceTransformedList() {
|
|
||||||
val codonTable = mapOf("ATT" to "Isoleucine", "CAA" to "Glutamine", "CGC" to "Arginine", "GGC" to "Glycine")
|
|
||||||
val dnaFragment = "ATTCGCGGCCGCCAA"
|
|
||||||
|
|
||||||
val proteins = dnaFragment.chunked(3) { codon ->
|
|
||||||
codonTable[codon.toString()] ?: error("Unknown codon")
|
|
||||||
}
|
|
||||||
|
|
||||||
assertIterableEquals(listOf("Isoleucine", "Arginine", "Glycine", "Arginine", "Glutamine"), proteins)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun givenListOfValues_whenChunking_thenProduceListOfArrays() {
|
|
||||||
val whole = listOf(1, 4, 7, 4753, 2, 34, 62, 76, 5868, 0)
|
|
||||||
val chunks = whole.chunked(6)
|
|
||||||
|
|
||||||
val expected = listOf(listOf(1, 4, 7, 4753, 2, 34), listOf(62, 76, 5868, 0))
|
|
||||||
|
|
||||||
assertIterableEquals(expected, chunks)
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -1,71 +0,0 @@
|
|||||||
package com.baeldung.filter
|
|
||||||
|
|
||||||
import org.junit.jupiter.api.Assertions.assertIterableEquals
|
|
||||||
import org.junit.jupiter.api.Test
|
|
||||||
|
|
||||||
internal class DistinctTest {
|
|
||||||
data class SmallClass(val key: String, val num: Int)
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun whenApplyingDistinct_thenReturnListOfNoDuplicateValues() {
|
|
||||||
val array = arrayOf(1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 5, 6, 7, 8, 9)
|
|
||||||
val result = array.distinct()
|
|
||||||
val expected = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9)
|
|
||||||
|
|
||||||
assertIterableEquals(expected, result)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun givenArrayOfClassObjects_whenApplyingDistinctOnClassProperty_thenReturnListDistinctOnThatValue() {
|
|
||||||
|
|
||||||
val original = arrayOf(
|
|
||||||
SmallClass("key1", 1),
|
|
||||||
SmallClass("key2", 2),
|
|
||||||
SmallClass("key3", 3),
|
|
||||||
SmallClass("key4", 3),
|
|
||||||
SmallClass("er", 9),
|
|
||||||
SmallClass("er", 10),
|
|
||||||
SmallClass("er", 11))
|
|
||||||
|
|
||||||
val actual = original.distinctBy { it.key }
|
|
||||||
|
|
||||||
val expected = listOf(
|
|
||||||
SmallClass("key1", 1),
|
|
||||||
SmallClass("key2", 2),
|
|
||||||
SmallClass("key3", 3),
|
|
||||||
SmallClass("key4", 3),
|
|
||||||
SmallClass("er", 9))
|
|
||||||
|
|
||||||
|
|
||||||
assertIterableEquals(expected, actual)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun givenArrayOfClassObjects_whenApplyingComplicatedSelector_thenReturnFirstElementToMatchEachSelectorValue() {
|
|
||||||
val array = arrayOf(
|
|
||||||
SmallClass("key1", 1),
|
|
||||||
SmallClass("key2", 2),
|
|
||||||
SmallClass("key3", 3),
|
|
||||||
SmallClass("key4", 3),
|
|
||||||
SmallClass("er", 9),
|
|
||||||
SmallClass("er", 10),
|
|
||||||
SmallClass("er", 11),
|
|
||||||
SmallClass("er", 11),
|
|
||||||
SmallClass("er", 91),
|
|
||||||
SmallClass("blob", 22),
|
|
||||||
SmallClass("dob", 27),
|
|
||||||
SmallClass("high", 201_434_314))
|
|
||||||
|
|
||||||
val actual = array.distinctBy { Math.floor(it.num / 10.0) }
|
|
||||||
|
|
||||||
val expected = listOf(
|
|
||||||
SmallClass("key1", 1),
|
|
||||||
SmallClass("er", 10),
|
|
||||||
SmallClass("er", 91),
|
|
||||||
SmallClass("blob", 22),
|
|
||||||
SmallClass("high", 201_434_314))
|
|
||||||
|
|
||||||
assertIterableEquals(expected, actual)
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -1,53 +0,0 @@
|
|||||||
package com.baeldung.filter
|
|
||||||
|
|
||||||
import org.junit.jupiter.api.Assertions.assertIterableEquals
|
|
||||||
import org.junit.jupiter.api.Test
|
|
||||||
|
|
||||||
internal class DropTest {
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun whenDroppingFirstTwoItemsOfArray_thenTwoLess() {
|
|
||||||
val array = arrayOf(1, 2, 3, 4)
|
|
||||||
val result = array.drop(2)
|
|
||||||
val expected = listOf(3, 4)
|
|
||||||
|
|
||||||
assertIterableEquals(expected, result)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun whenDroppingMoreItemsOfArray_thenEmptyList() {
|
|
||||||
val array = arrayOf(1, 2, 3, 4)
|
|
||||||
val result = array.drop(5)
|
|
||||||
val expected = listOf<Int>()
|
|
||||||
|
|
||||||
assertIterableEquals(expected, result)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun givenArray_whenDroppingLastElement_thenReturnListWithoutLastElement() {
|
|
||||||
val array = arrayOf("1", "2", "3", "4")
|
|
||||||
val result = array.dropLast(1)
|
|
||||||
val expected = listOf("1", "2", "3")
|
|
||||||
|
|
||||||
assertIterableEquals(expected, result)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun givenArrayOfFloats_whenDroppingLastUntilPredicateIsFalse_thenReturnSubsetListOfFloats() {
|
|
||||||
val array = arrayOf(1f, 1f, 1f, 1f, 1f, 2f, 1f, 1f, 1f)
|
|
||||||
val result = array.dropLastWhile { it == 1f }
|
|
||||||
val expected = listOf(1f, 1f, 1f, 1f, 1f, 2f)
|
|
||||||
|
|
||||||
assertIterableEquals(expected, result)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun givenList_whenDroppingMoreThanAvailable_thenThrowException() {
|
|
||||||
val list = listOf('a', 'e', 'i', 'o', 'u')
|
|
||||||
val result = list.drop(6)
|
|
||||||
val expected: List<String> = listOf()
|
|
||||||
|
|
||||||
assertIterableEquals(expected, result)
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -1,39 +0,0 @@
|
|||||||
package com.baeldung.filter
|
|
||||||
|
|
||||||
import org.apache.commons.math3.primes.Primes
|
|
||||||
import org.junit.jupiter.api.Assertions.assertIterableEquals
|
|
||||||
import org.junit.jupiter.api.Test
|
|
||||||
import kotlin.test.assertTrue
|
|
||||||
|
|
||||||
internal class FilterTest {
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun givenAscendingValueMap_whenFilteringOnValue_ThenReturnSubsetOfMap() {
|
|
||||||
val originalMap = mapOf("key1" to 1, "key2" to 2, "key3" to 3)
|
|
||||||
val filteredMap = originalMap.filter { it.value < 2 }
|
|
||||||
val expectedMap = mapOf("key1" to 1)
|
|
||||||
|
|
||||||
assertTrue { expectedMap == filteredMap }
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun givenSeveralCollections_whenFilteringToAccumulativeList_thenListContainsAllContents() {
|
|
||||||
val array1 = arrayOf(90, 92, 93, 94, 92, 95, 93)
|
|
||||||
val array2 = sequenceOf(51, 31, 83, 674_506_111, 256_203_161, 15_485_863)
|
|
||||||
val list1 = listOf(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
|
|
||||||
val primes = mutableListOf<Int>()
|
|
||||||
|
|
||||||
val expected = listOf(2, 3, 5, 7, 31, 83, 15_485_863, 256_203_161, 674_506_111)
|
|
||||||
|
|
||||||
val primeCheck = { num: Int -> Primes.isPrime(num) }
|
|
||||||
|
|
||||||
array1.filterTo(primes, primeCheck)
|
|
||||||
list1.filterTo(primes, primeCheck)
|
|
||||||
array2.filterTo(primes, primeCheck)
|
|
||||||
|
|
||||||
primes.sort()
|
|
||||||
|
|
||||||
assertIterableEquals(expected, primes)
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -1,45 +0,0 @@
|
|||||||
package com.baeldung.filter
|
|
||||||
|
|
||||||
import org.junit.jupiter.api.Assertions.assertIterableEquals
|
|
||||||
import org.junit.jupiter.api.Assertions.assertThrows
|
|
||||||
import org.junit.jupiter.api.Test
|
|
||||||
|
|
||||||
internal class SliceTest {
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun whenSlicingAnArrayWithDotRange_ThenListEqualsTheSlice() {
|
|
||||||
val original = arrayOf(1, 2, 3, 2, 1)
|
|
||||||
val actual = original.slice(1..3)
|
|
||||||
val expected = listOf(2, 3, 2)
|
|
||||||
|
|
||||||
assertIterableEquals(expected, actual)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun whenSlicingAnArrayWithDownToRange_thenListMadeUpOfReverseSlice() {
|
|
||||||
val original = arrayOf(1, 2, 3, 2, 1)
|
|
||||||
val actual = original.slice(3 downTo 0)
|
|
||||||
val expected = listOf(2, 3, 2, 1)
|
|
||||||
|
|
||||||
assertIterableEquals(expected, actual)
|
|
||||||
}
|
|
||||||
|
|
||||||
// From the 1.3 version of Kotlin APIs, slice doesn't return array of nulls but throw IndexOutOfBoundsException
|
|
||||||
// @Test
|
|
||||||
// fun whenSlicingBeyondTheRangeOfTheArray_thenContainManyNulls() {
|
|
||||||
// val original = arrayOf(12, 3, 34, 4)
|
|
||||||
// val actual = original.slice(3..8)
|
|
||||||
// val expected = listOf(4, null, null, null, null, null)
|
|
||||||
//
|
|
||||||
// assertIterableEquals(expected, actual)
|
|
||||||
// }
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun whenSlicingBeyondRangeOfArrayWithStep_thenOutOfBoundsException() {
|
|
||||||
assertThrows(ArrayIndexOutOfBoundsException::class.java) {
|
|
||||||
val original = arrayOf(12, 3, 34, 4)
|
|
||||||
original.slice(3..8 step 2)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user