[Java 11502] (#12625)

* [JAVA-11502] Added vavr-modules (parent)

* [JAVA-11502] Added vavr(submodule) to vavr-modules(parent)

* [JAVA-11502] Added vavr-2(submodule) to vavr-modules(parent)

* [JAVA-11502] Added java-vavr-stream(submodule) to vavr-modules(parent)

* [JAVA-11502] deleted modules that were moved + cleanup

Co-authored-by: panagiotiskakos <panagiotis.kakos@libra-is.com>
Co-authored-by: Dhawal Kapil <dhawalkapil@gmail.com>
This commit is contained in:
panos-kakos
2022-08-25 16:47:55 +01:00
committed by GitHub
parent 5405306118
commit eb1f4797a7
40 changed files with 239 additions and 206 deletions

3
vavr-modules/README.md Normal file
View File

@@ -0,0 +1,3 @@
## VAVR
This module contains modules about vavr.

View File

@@ -0,0 +1,8 @@
## Vavr Streams
This module contains articles about streams in Vavr.
### Relevant Articles:
- [Java Streams vs Vavr Streams](https://www.baeldung.com/vavr-java-streams)

View File

@@ -0,0 +1,30 @@
<?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>
<groupId>com.baeldung.samples</groupId>
<artifactId>java-vavr-stream</artifactId>
<version>1.0</version>
<name>java-vavr-stream</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>vavr-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>io.vavr</groupId>
<artifactId>vavr</artifactId>
<version>${io.vavr.version}</version>
</dependency>
</dependencies>
<properties>
<io.vavr.version>0.9.2</io.vavr.version>
</properties>
</project>

View File

@@ -0,0 +1,98 @@
package com.baeldung.samples.java.vavr;
import io.vavr.collection.Stream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.IntStream;
/**
*
* @author baeldung
*/
public class VavrSampler {
static int[] intArray = new int[]{1, 2, 4};
static List<Integer> intList = new ArrayList<Integer>();
static int[][] intOfInts = new int[][]{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
public static void main(String[] args) {
vavrStreamElementAccess();
System.out.println("====================================");
vavrParallelStreamAccess();
System.out.println("====================================");
jdkFlatMapping();
System.out.println("====================================");
vavrStreamManipulation();
System.out.println("====================================");
vavrStreamDistinct();
}
public static void vavrStreamElementAccess() {
System.out.println("Vavr Element Access");
System.out.println("====================================");
Stream<Integer> vavredStream = Stream.ofAll(intArray);
System.out.println("Vavr index access: " + vavredStream.get(2));
System.out.println("Vavr head element access: " + vavredStream.get());
Stream<String> vavredStringStream = Stream.of("foo", "bar", "baz");
System.out.println("Find foo " + vavredStringStream.indexOf("foo"));
}
public static void vavrParallelStreamAccess() {
try {
System.out.println("Vavr Stream Concurrent Modification");
System.out.println("====================================");
Stream<Integer> vavrStream = Stream.ofAll(intList);
intList.add(5);
vavrStream.forEach(i -> System.out.println("in a Vavr Stream: " + i));
} catch (Exception ex) {
ex.printStackTrace();
}
Stream<Integer> wrapped = Stream.ofAll(intArray);
intArray[2] = 5;
wrapped.forEach(i -> System.out.println("Vavr looped " + i));
}
public static void jdkFlatMapping() {
System.out.println("JDK FlatMap -> Uncomment line 68 to test");
System.out.println("====================================");
int[][] intOfInts = new int[][]{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
IntStream mapToInt = Arrays.stream(intOfInts)
.map(intArr -> Arrays.stream(intArr))
.flatMapToInt(val -> val.map(n -> {
return n * n;
}))
.peek(n -> System.out.println("Peeking at " + n));
//Uncomment to execute pipeline
//mapToInt.forEach(n -> System.out.println("FlatMapped Result "+n));
}
public static void vavrStreamManipulation() {
System.out.println("Vavr Stream Manipulation");
System.out.println("====================================");
List<String> stringList = new ArrayList<>();
stringList.add("foo");
stringList.add("bar");
stringList.add("baz");
Stream<String> vavredStream = Stream.ofAll(stringList);
vavredStream.forEach(item -> System.out.println("Vavr Stream item: " + item));
Stream<String> vavredStream2 = vavredStream.insert(2, "buzz");
vavredStream2.forEach(item -> System.out.println("Vavr Stream item after stream addition: " + item));
stringList.forEach(item -> System.out.println("List item after stream addition: " + item));
Stream<String> deletionStream = vavredStream.remove("bar");
deletionStream.forEach(item -> System.out.println("Vavr Stream item after stream item deletion: " + item));
}
public static void vavrStreamDistinct() {
Stream<String> vavredStream = Stream.of("foo", "bar", "baz", "buxx", "bar", "bar", "foo");
Stream<String> distinctVavrStream = vavredStream.distinctBy((y, z) -> {
return y.compareTo(z);
});
distinctVavrStream.forEach(item -> System.out.println("Vavr Stream item after distinct query " + item));
}
}

View File

@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

33
vavr-modules/pom.xml Normal file
View File

@@ -0,0 +1,33 @@
<?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>vavr-modules</artifactId>
<name>vavr-modules</name>
<packaging>pom</packaging>
<parent>
<artifactId>parent-modules</artifactId>
<groupId>com.baeldung</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<modules>
<module>vavr</module>
<module>vavr-2</module>
<module>java-vavr-stream</module>
</modules>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>

View File

@@ -0,0 +1,8 @@
## Vavr
This module contains articles about Vavr.
### Relevant Articles:
- [Introduction to Vavrs Either](https://www.baeldung.com/vavr-either)
- [Interoperability Between Java and Vavr](https://www.baeldung.com/java-vavr)
- [[<-- prev]](/vavr)

View File

@@ -0,0 +1,27 @@
<?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>vavr-2</artifactId>
<name>vavr-2</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>vavr-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>io.vavr</groupId>
<artifactId>vavr-test</artifactId>
<version>${vavr.version}</version>
</dependency>
</dependencies>
<properties>
<vavr.version>0.9.1</vavr.version>
</properties>
</project>

View File

@@ -0,0 +1,37 @@
package com.baeldung.vavr.either;
import java.util.HashMap;
import java.util.Map;
import io.vavr.control.Either;
public class EitherDemo {
public static Object[] computeWithoutEitherUsingArray(int marks) {
Object[] results = new Object[2];
if (marks < 85) {
results[0] = "Marks not acceptable";
} else {
results[1] = marks;
}
return results;
}
public static Map<String, Object> computeWithoutEitherUsingMap(int marks) {
Map<String, Object> results = new HashMap<>();
if (marks < 85) {
results.put("FAILURE", "Marks not acceptable");
} else {
results.put("SUCCESS", marks);
}
return results;
}
static Either<String, Integer> computeWithEither(int marks) {
if (marks < 85) {
return Either.left("Marks not acceptable");
} else {
return Either.right(marks);
}
}
}

View File

@@ -0,0 +1,38 @@
package com.baeldung.vavr.either;
import io.vavr.control.Either;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class EitherUnitTest {
@Test
public void givenMarks_whenPassNumber_thenExpectNumber() {
Either<String, Integer> result = EitherDemo.computeWithEither(100);
int marks = result.right()
.getOrElseThrow(x -> new IllegalStateException());
assertEquals(100, marks);
}
@Test
public void givenMarks_whenFailNumber_thenExpectErrorMesssage() {
Either<String, Integer> result = EitherDemo.computeWithEither(50);
String error = result.left()
.getOrNull();
assertEquals("Marks not acceptable", error);
}
@Test
public void givenPassMarks_whenModified_thenExpectNumber() {
Either<String, Integer> result = EitherDemo.computeWithEither(90);
int marks = result.right()
.map(x -> x * 2)
.get();
assertEquals(180, marks);
}
}

View File

@@ -0,0 +1,93 @@
package com.baeldung.vavr.interoperability;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import java.util.Optional;
import org.junit.Test;
import io.vavr.collection.HashMap;
import io.vavr.collection.LinkedHashSet;
import io.vavr.collection.List;
import io.vavr.collection.Map;
import io.vavr.collection.Set;
import io.vavr.collection.Stream;
public class CollectionsInteroperabilityUnitTest {
@Test
public void givenParams_whenVavrList_thenReturnJavaList() {
List<String> vavrStringList = List.of("JAVA", "Javascript", "Scala");
java.util.List<String> javaStringList = vavrStringList.toJavaList();
assertTrue(javaStringList instanceof java.util.List);
}
@Test
public void givenParams_whenVavrStream_thenReturnJavaStream() {
Stream<String> vavrStream = Stream.of("JAVA", "Javascript", "Scala");
java.util.stream.Stream<String> javaParallelStream = vavrStream.toJavaParallelStream();
assertTrue(javaParallelStream instanceof java.util.stream.Stream);
java.util.List<String> javaStringList = vavrStream.toJavaList();
assertTrue(javaStringList instanceof java.util.List);
}
@Test
public void givenParams_whenVavrMap_thenReturnJavaMap() {
Map<String, String> vavrMap = HashMap.of("1", "a", "2", "b", "3", "c");
java.util.Map<String, String> javaMap = vavrMap.toJavaMap();
assertTrue(javaMap instanceof java.util.Map);
}
@Test
public void givenParams_whenJavaList_thenReturnVavrListUsingOfAll() {
java.util.List<String> javaList = Arrays.asList("Java", "Haskell", "Scala");
List<String> vavrList = List.ofAll(javaList);
assertTrue(vavrList instanceof io.vavr.collection.List);
}
@Test
public void givenParams_whenJavaStream_thenReturnVavrListUsingOfAll() {
java.util.stream.Stream<String> javaStream = Arrays.asList("Java", "Haskell", "Scala")
.stream();
Stream<String> vavrStream = Stream.ofAll(javaStream);
assertTrue(vavrStream instanceof io.vavr.collection.Stream);
}
@Test(expected = UnsupportedOperationException.class)
public void givenParams_whenVavrListConverted_thenException() {
java.util.List<String> javaList = List.of("Java", "Haskell", "Scala")
.asJava();
javaList.add("Python");
assertEquals(4, javaList.size());
}
@Test
public void givenParams_whenVavrListConvertedToMutable_thenRetunMutableList() {
java.util.List<String> javaList = List.of("Java", "Haskell", "Scala")
.asJavaMutable();
javaList.add("Python");
assertEquals(4, javaList.size());
}
@Test
public void givenParams_WhenVavarListConvertedToLinkedSet_thenReturnLinkedSet() {
List<String> vavrList = List.of("Java", "Haskell", "Scala", "Java");
Set<String> linkedSet = vavrList.toLinkedSet();
assertEquals(3, linkedSet.size());
assertTrue(linkedSet instanceof LinkedHashSet);
}
@Test
public void givenParams_WhenVavrList_thenReturnJavaOptional() {
List<String> vavrList = List.of("Java");
Optional<String> optional = vavrList.toJavaOptional();
assertEquals("Java", optional.get());
}
}

View File

@@ -0,0 +1,16 @@
## Vavr
This module contains articles about Vavr.
### Relevant Articles:
- [Introduction to Vavr](https://www.baeldung.com/vavr)
- [Guide to Try in Vavr](https://www.baeldung.com/vavr-try)
- [Guide to Pattern Matching in Vavr](https://www.baeldung.com/vavr-pattern-matching)
- [Property Testing Example With Vavr](https://www.baeldung.com/vavr-property-testing)
- [Exceptions in Lambda Expression Using Vavr](https://www.baeldung.com/exceptions-using-vavr)
- [Vavr Support in Spring Data](https://www.baeldung.com/spring-vavr)
- [Introduction to Vavrs Validation API](https://www.baeldung.com/vavr-validation-api)
- [Guide to Collections API in Vavr](https://www.baeldung.com/vavr-collections)
- [Collection Factory Methods for Vavr](https://www.baeldung.com/vavr-collection-factory-methods)
- [Introduction to Future in Vavr](https://www.baeldung.com/vavr-future)
- [[next -->]](/vavr-2)

49
vavr-modules/vavr/pom.xml Normal file
View File

@@ -0,0 +1,49 @@
<?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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>vavr</artifactId>
<version>1.0</version>
<name>vavr</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-boot-2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-boot-2</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>io.vavr</groupId>
<artifactId>vavr-test</artifactId>
<version>${vavr.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.awaitility</groupId>
<artifactId>awaitility</artifactId>
<version>${awaitility.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<vavr.version>0.9.1</vavr.version>
<awaitility.version>3.0.0</awaitility.version>
</properties>
</project>

View File

@@ -0,0 +1,11 @@
package com.baeldung;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}

View File

@@ -0,0 +1,18 @@
package com.baeldung.repositories;
import org.springframework.data.repository.Repository;
import com.baeldung.vavr.User;
import io.vavr.collection.Seq;
import io.vavr.control.Option;
public interface VavrUserRepository extends Repository<User, Long> {
Option<User> findById(long id);
Seq<User> findByName(String name);
User save(User user);
}

View File

@@ -0,0 +1,99 @@
package com.baeldung.samples.java.vavr;
import java.util.ArrayList;
import java.util.List;
import io.vavr.collection.Stream;
/**
*
* @author baeldung
*/
public class VavrSampler {
static int[] intArray = new int[] { 1, 2, 4 };
static List<Integer> intList = new ArrayList<>();
static int[][] intOfInts = new int[][] { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
public static void main(String[] args) {
vavrStreamElementAccess();
System.out.println("====================================");
vavrParallelStreamAccess();
System.out.println("====================================");
vavrFlatMapping();
System.out.println("====================================");
vavrStreamManipulation();
System.out.println("====================================");
vavrStreamDistinct();
}
public static void vavrStreamElementAccess() {
System.out.println("Vavr Element Access");
System.out.println("====================================");
Stream<Integer> vavredStream = Stream.ofAll(intArray);
System.out.println("Vavr index access: " + vavredStream.get(2));
System.out.println("Vavr head element access: " + vavredStream.get());
Stream<String> vavredStringStream = Stream.of("foo", "bar", "baz");
System.out.println("Find foo " + vavredStringStream.indexOf("foo"));
}
public static void vavrParallelStreamAccess() {
System.out.println("Vavr Stream Concurrent Modification");
System.out.println("====================================");
Stream<Integer> vavrStream = Stream.ofAll(intList);
// intList.add(5);
vavrStream.forEach(i -> System.out.println("in a Vavr Stream: " + i));
// Stream<Integer> wrapped = Stream.ofAll(intArray);
// intArray[2] = 5;
// wrapped.forEach(i -> System.out.println("Vavr looped " + i));
}
public static void jdkFlatMapping() {
System.out.println("Java flatMapping");
System.out.println("====================================");
java.util.stream.Stream.of(42).flatMap(i -> java.util.stream.Stream.generate(() -> {
System.out.println("nested call");
return 42;
})).findAny();
}
public static void vavrFlatMapping() {
System.out.println("Vavr flatMapping");
System.out.println("====================================");
Stream.of(42)
.flatMap(i -> Stream.continually(() -> {
System.out.println("nested call");
return 42;
}))
.get(0);
}
public static void vavrStreamManipulation() {
System.out.println("Vavr Stream Manipulation");
System.out.println("====================================");
List<String> stringList = new ArrayList<>();
stringList.add("foo");
stringList.add("bar");
stringList.add("baz");
Stream<String> vavredStream = Stream.ofAll(stringList);
vavredStream.forEach(item -> System.out.println("Vavr Stream item: " + item));
Stream<String> vavredStream2 = vavredStream.insert(2, "buzz");
vavredStream2.forEach(item -> System.out.println("Vavr Stream item after stream addition: " + item));
stringList.forEach(item -> System.out.println("List item after stream addition: " + item));
Stream<String> deletionStream = vavredStream.remove("bar");
deletionStream.forEach(item -> System.out.println("Vavr Stream item after stream item deletion: " + item));
}
public static void vavrStreamDistinct() {
Stream<String> vavredStream = Stream.of("foo", "bar", "baz", "buxx", "bar", "bar", "foo");
Stream<String> distinctVavrStream = vavredStream.distinctBy((y, z) -> {
return y.compareTo(z);
});
distinctVavrStream.forEach(item -> System.out.println("Vavr Stream item after distinct query " + item));
}
}

View File

@@ -0,0 +1,38 @@
package com.baeldung.vavr;
public class Person {
private String name;
private int age;
Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
public Person() {
super();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
}

View File

@@ -0,0 +1,22 @@
package com.baeldung.vavr;
import io.vavr.collection.Seq;
import io.vavr.control.Validation;
class PersonValidator {
private static final String NAME_ERR = "Invalid characters in name: ";
private static final String AGE_ERR = "Age must be at least 0";
Validation<Seq<String>, Person> validatePerson(String name, int age) {
return Validation.combine(validateName(name), validateAge(age)).ap(Person::new);
}
private Validation<String, String> validateName(String name) {
String invalidChars = name.replaceAll("[a-zA-Z ]", "");
return invalidChars.isEmpty() ? Validation.valid(name) : Validation.invalid(NAME_ERR + invalidChars);
}
private Validation<String, Integer> validateAge(int age) {
return age < 0 ? Validation.invalid(AGE_ERR) : Validation.valid(age);
}
}

View File

@@ -0,0 +1,32 @@
package com.baeldung.vavr;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String name;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

View File

@@ -0,0 +1,21 @@
package com.baeldung.vavr.exception.handling;
import com.baeldung.vavr.exception.handling.client.ClientException;
import com.baeldung.vavr.exception.handling.client.HttpClient;
import com.baeldung.vavr.exception.handling.client.Response;
public class JavaTryCatch {
private HttpClient httpClient;
public JavaTryCatch(HttpClient httpClient) {
this.httpClient = httpClient;
}
public Response getResponse() {
try {
return httpClient.call();
} catch (ClientException e) {
return null;
}
}
}

View File

@@ -0,0 +1,18 @@
package com.baeldung.vavr.exception.handling;
import com.baeldung.vavr.exception.handling.client.HttpClient;
import com.baeldung.vavr.exception.handling.client.Response;
import io.vavr.control.Try;
class VavrTry {
private final HttpClient httpClient;
VavrTry(HttpClient httpClient) {
this.httpClient = httpClient;
}
Try<Response> getResponse() {
return Try.of(httpClient::call);
}
}

View File

@@ -0,0 +1,8 @@
package com.baeldung.vavr.exception.handling.client;
public class ClientException extends Exception {
public ClientException(String message) {
super(message);
}
}

View File

@@ -0,0 +1,6 @@
package com.baeldung.vavr.exception.handling.client;
public interface HttpClient {
Response call() throws ClientException;
}

View File

@@ -0,0 +1,9 @@
package com.baeldung.vavr.exception.handling.client;
public class Response {
public final String id;
public Response(String id) {
this.id = id;
}
}

View File

@@ -0,0 +1,17 @@
package com.baeldung.vavrvalidation.application;
import com.baeldung.vavrvalidation.model.User;
import com.baeldung.vavrvalidation.validator.UserValidator;
import io.vavr.collection.Seq;
import io.vavr.control.Validation;
public class Application {
public static void main(String[] args) {
UserValidator userValidator = new UserValidator();
Validation<Seq<String>, User> validation = userValidator.validateUser("John", "john@domain.com");
// process validation results here
}
}

View File

@@ -0,0 +1,18 @@
package com.baeldung.vavrvalidation.model;
public class User {
private String name;
private String email;
public User(String name, String email) {
this.name = name;
this.email = email;
}
@Override
public String toString() {
return "User [name=" + name + ", email=" + email + "]";
}
// standard setters and getters
}

View File

@@ -0,0 +1,29 @@
package com.baeldung.vavrvalidation.validator;
import com.baeldung.vavrvalidation.model.User;
import io.vavr.collection.CharSeq;
import io.vavr.collection.Seq;
import io.vavr.control.Validation;
public class UserValidator {
private static final String NAME_PATTERN = "^[a-zA-Z0-9]+$";
private static final String NAME_ERROR = "Name contains invalid characters";
private static final String EMAIL_PATTERN =
"^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
private static final String EMAIL_ERROR = "Email must be a well-formed email address";
public Validation<Seq<String>, User> validateUser(String name, String email) {
return Validation
.combine(validateField(name, NAME_PATTERN, NAME_ERROR)
,validateField(email, EMAIL_PATTERN, EMAIL_ERROR))
.ap(User::new);
}
private Validation<String, String> validateField(String field, String pattern, String error) {
return CharSeq.of(field).replaceAll(pattern, "").transform(seq -> seq.isEmpty()
? Validation.valid(field)
: Validation.invalid(error));
}
}

View File

@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@@ -0,0 +1,116 @@
package com.baeldung.vavr;
import io.vavr.MatchError;
import io.vavr.control.Option;
import org.junit.Test;
import static io.vavr.API.$;
import static io.vavr.API.Case;
import static io.vavr.API.Match;
import static io.vavr.API.run;
import static io.vavr.Predicates.allOf;
import static io.vavr.Predicates.anyOf;
import static io.vavr.Predicates.instanceOf;
import static io.vavr.Predicates.is;
import static io.vavr.Predicates.isIn;
import static io.vavr.Predicates.isNotNull;
import static io.vavr.Predicates.isNull;
import static io.vavr.Predicates.noneOf;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class PatternMatchingUnitTest {
@Test
public void whenMatchesDefault_thenCorrect() {
int input = 5;
String output = Match(input).of(Case($(1), "one"), Case($(2), "two"), Case($(3), "three"), Case($(), "unknown"));
assertEquals("unknown", output);
}
@Test(expected = MatchError.class)
public void givenNoMatchAndNoDefault_whenThrows_thenCorrect() {
int input = 5;
Match(input).of(Case($(1), "one"), Case($(2), "two"));
}
@Test
public void whenMatchWorksWithOption_thenCorrect() {
int i = 10;
Option<String> s = Match(i).option(Case($(0), "zero"));
assertTrue(s.isEmpty());
assertEquals("None", s.toString());
}
@Test
public void whenMatchWorksWithPredicate_thenCorrect() {
int i = 3;
String s = Match(i).of(Case($(is(1)), "one"), Case($(is(2)), "two"), Case($(is(3)), "three"), Case($(), "?"));
assertEquals("three", s);
}
@Test
public void givenInput_whenMatchesClass_thenCorrect() {
Object obj = 5;
String s = Match(obj).of(Case($(instanceOf(String.class)), "string matched"), Case($(), "not string"));
assertEquals("not string", s);
}
@Test
public void givenInput_whenMatchesNull_thenCorrect() {
Object obj = 5;
String s = Match(obj).of(Case($(isNull()), "no value"), Case($(isNotNull()), "value found"));
assertEquals("value found", s);
}
@Test
public void givenInput_whenContainsWorks_thenCorrect() {
int i = 5;
String s = Match(i).of(Case($(isIn(2, 4, 6, 8)), "Even Single Digit"), Case($(isIn(1, 3, 5, 7, 9)), "Odd Single Digit"), Case($(), "Out of range"));
assertEquals("Odd Single Digit", s);
}
@Test
public void givenInput_whenMatchAllWorks_thenCorrect() {
Integer i = null;
String s = Match(i).of(Case($(allOf(isNotNull(), isIn(1, 2, 3, null))), "Number found"), Case($(), "Not found"));
assertEquals("Not found", s);
}
@Test
public void givenInput_whenMatchesAnyOfWorks_thenCorrect() {
Integer year = 1990;
String s = Match(year).of(Case($(anyOf(isIn(1990, 1991, 1992), is(1986))), "Age match"), Case($(), "No age match"));
assertEquals("Age match", s);
}
@Test
public void givenInput_whenMatchesNoneOfWorks_thenCorrect() {
Integer year = 1990;
String s = Match(year).of(Case($(noneOf(isIn(1990, 1991, 1992), is(1986))), "Age match"), Case($(), "No age match"));
assertEquals("No age match", s);
}
@Test
public void whenMatchWorksWithPredicate_thenCorrect2() {
int i = 5;
String s = Match(i).of(Case($(isIn(2, 4, 6, 8)), "Even Single Digit"), Case($(isIn(1, 3, 5, 7, 9)), "Odd Single Digit"), Case($(), "Out of range"));
assertEquals("Odd Single Digit", s);
}
@Test
public void whenMatchCreatesSideEffects_thenCorrect() {
int i = 4;
Match(i).of(Case($(isIn(2, 4, 6, 8)), o -> run(this::displayEven)), Case($(isIn(1, 3, 5, 7, 9)), o -> run(this::displayOdd)), Case($(), o -> run(() -> {
throw new IllegalArgumentException(String.valueOf(i));
})));
}
private void displayEven() {
System.out.println("Input is even");
}
private void displayOdd() {
System.out.println("Input is odd");
}
}

View File

@@ -0,0 +1,73 @@
package com.baeldung.vavr;
import io.vavr.CheckedFunction1;
import io.vavr.collection.Stream;
import io.vavr.test.Arbitrary;
import io.vavr.test.CheckResult;
import io.vavr.test.Property;
import org.junit.Test;
import java.util.function.Predicate;
import static io.vavr.API.$;
import static io.vavr.API.Case;
import static io.vavr.API.Match;
public class PropertyBasedLongRunningUnitTest {
private static Predicate<Integer> divisibleByTwo = i -> i % 2 == 0;
private static Predicate<Integer> divisibleByFive = i -> i % 5 == 0;
private Stream<String> stringsSupplier() {
return Stream.from(0).map(i -> Match(i).of(
Case($(divisibleByFive.and(divisibleByTwo)), "DividedByTwoAndFiveWithoutRemainder"),
Case($(divisibleByFive), "DividedByFiveWithoutRemainder"),
Case($(divisibleByTwo), "DividedByTwoWithoutRemainder"),
Case($(), "")));
}
@Test
public void givenArbitrarySeq_whenCheckThatEverySecondElementIsEqualToString_thenTestPass() {
//given
Arbitrary<Integer> multiplesOf2 = Arbitrary
.integer()
.filter(i -> i > 0)
.filter(i -> i % 2 == 0 && i % 5 != 0);
//when
CheckedFunction1<Integer, Boolean> mustEquals = i -> stringsSupplier()
.get(i)
.equals("DividedByTwoWithoutRemainder");
//then
CheckResult result = Property
.def("Every second element must equal to DividedByTwoWithoutRemainder")
.forAll(multiplesOf2)
.suchThat(mustEquals)
.check(10_000, 100);
result.assertIsSatisfied();
}
@Test
public void givenArbitrarySeq_whenCheckThatEveryFifthElementIsEqualToString_thenTestPass() {
//given
Arbitrary<Integer> multiplesOf5 = Arbitrary
.integer()
.filter(i -> i > 0)
.filter(i -> i % 5 == 0 && i % 2 == 0);
//when
CheckedFunction1<Integer, Boolean> mustEquals = i -> stringsSupplier()
.get(i)
.endsWith("DividedByTwoAndFiveWithoutRemainder");
//then
Property
.def("Every fifth element must equal to DividedByTwoAndFiveWithoutRemainder")
.forAll(multiplesOf5)
.suchThat(mustEquals)
.check(10_000, 1_000)
.assertIsSatisfied();
}
}

View File

@@ -0,0 +1,371 @@
package com.baeldung.vavr;
import io.vavr.Function0;
import io.vavr.Function1;
import io.vavr.Function2;
import io.vavr.Function5;
import io.vavr.Lazy;
import io.vavr.Tuple;
import io.vavr.Tuple2;
import io.vavr.Tuple3;
import io.vavr.collection.List;
import io.vavr.collection.Seq;
import io.vavr.control.Option;
import io.vavr.control.Try;
import io.vavr.control.Validation;
import org.junit.Test;
import java.util.Arrays;
import java.util.Collections;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.stream.IntStream;
import static io.vavr.API.$;
import static io.vavr.API.Case;
import static io.vavr.API.Match;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
public class VavrUnitTest {
@Test
public void givenList_whenSorts_thenCorrect() {
List<Integer> sortedList = List.of(3, 2, 1)
.sorted();
}
/*
* Tuples
*/
// creating and element access
@Test
public void whenCreatesTuple_thenCorrect1() {
Tuple2<String, Integer> java8 = Tuple.of("Java", 8);
String element1 = java8._1;
int element2 = java8._2();
assertEquals("Java", element1);
assertEquals(8, element2);
}
@Test
public void whenCreatesTuple_thenCorrect2() {
Tuple3<String, Integer, Double> java8 = Tuple.of("Java", 8, 1.8);
String element1 = java8._1;
int element2 = java8._2();
double element3 = java8._3();
assertEquals("Java", element1);
assertEquals(8, element2);
assertEquals(1.8, element3, 0.1);
}
// mapping--component-wise(using Function interface)
@Test
public void givenTuple_whenMapsComponentWise_thenCorrect() {
Tuple2<String, Integer> java8 = Tuple.of("Java", 8);
Tuple2<String, Integer> mapOfJava8 = java8.map(s -> s + "Vavr", i -> i / 2);
int num = mapOfJava8._2();
assertEquals("JavaVavr", mapOfJava8._1);
assertEquals(4, num);
}
// mapping--with one mapper(using BiFunction interface)
@Test
public void givenTuple_whenMapsWithOneMapper_thenCorrect() {
Tuple2<String, Integer> java8 = Tuple.of("Java", 8);
Tuple2<String, Integer> mapOfJava8 = java8.map((s, i) -> Tuple.of(s + "Vavr", i / 2));
int num = mapOfJava8._2();
assertEquals("JavaVavr", mapOfJava8._1);
assertEquals(4, num);
}
// transforming a tuple
@Test
public void givenTuple_whenTransforms_thenCorrect() {
Tuple2<String, Integer> java8 = Tuple.of("Java", 8);
String transformed = java8.apply((s, i) -> s + "Vavr " + i / 2);
assertEquals("JavaVavr 4", transformed);
}
@Test
public void editTupleValueForNewTupleInstance(){
final Tuple2<String, Integer> java9 = Tuple.of("Java", 8);
final Tuple2<String, Integer> transformed = java9.update2(9);
int num = transformed._2();
assertEquals(9,num);
}
@Test
public void editTupleValueForSameInstance(){
Tuple2<String, Integer> java9 = Tuple.of("Java", 8);
java9 = java9.update2(9);
final int num = java9._2();
assertEquals(9,num);
}
@Test
public void getNumberOfElementTuple(){
Tuple2<String, Integer> java8 = Tuple.of("Java", 8);
Tuple3<String, Integer, Double> java8Triple = Tuple.of("Java", 8, 1.8);
Tuple3<String, Integer, Double> java8TripleWnull = Tuple.of("Java", null, 1.8);
int num = java8.arity();
int numTriple = java8Triple.arity();
int numTripleWnull = java8TripleWnull.arity();
assertEquals(2,num);
assertEquals(3,numTriple);
assertEquals(3,numTripleWnull);
}
/*
* Functions
*/
@Test
public void givenJava8Function_whenWorks_thenCorrect() {
Function<Integer, Integer> square = (num) -> num * num;
int result = square.apply(2);
assertEquals(4, result);
}
@Test
public void givenJava8BiFunction_whenWorks_thenCorrect() {
BiFunction<Integer, Integer, Integer> sum = (num1, num2) -> num1 + num2;
int result = sum.apply(5, 7);
assertEquals(12, result);
}
@Test
public void givenVavrFunction_whenWorks_thenCorrect() {
Function1<Integer, Integer> square = (num) -> num * num;
Integer result = square.apply(2);
assertEquals(Integer.valueOf(4), result);
}
@Test
public void givenVavrBiFunction_whenWorks_thenCorrect() {
Function2<Integer, Integer, Integer> sum = (num1, num2) -> num1 + num2;
Integer result = sum.apply(5, 7);
assertEquals(Integer.valueOf(12), result);
}
@Test
public void whenCreatesFunction_thenCorrect0() {
Function0<String> getClazzName = () -> this.getClass()
.getName();
String clazzName = getClazzName.apply();
assertEquals("com.baeldung.vavr.VavrUnitTest", clazzName);
}
@Test
public void whenCreatesFunction_thenCorrect2() {
Function2<Integer, Integer, Integer> sum = (a, b) -> a + b;
int summed = sum.apply(5, 6);
assertEquals(11, summed);
}
@Test
public void whenCreatesFunction_thenCorrect5() {
Function5<String, String, String, String, String, String> concat = (a, b, c, d, e) -> a + b + c + d + e;
String finalString = concat.apply("Hello ", "world", "! ", "Learn ", "Vavr");
assertEquals("Hello world! Learn Vavr", finalString);
}
@Test
public void whenCreatesFunctionFromMethodRef_thenCorrect() {
Function2<Integer, Integer, Integer> sum = Function2.of(this::sum);
int summed = sum.apply(5, 6);
assertEquals(11, summed);
}
public int sum(int a, int b) {
return a + b;
}
/*
* Values
*/
// option
@Test
public void givenValue_whenNullCheckNeeded_thenCorrect() {
Object possibleNullObj = null;
if (possibleNullObj == null)
possibleNullObj = "someDefaultValue";
assertNotNull(possibleNullObj);
}
@Test(expected = NullPointerException.class)
public void givenValue_whenNullCheckNeeded_thenCorrect2() {
Object possibleNullObj = null;
assertEquals("somevalue", possibleNullObj.toString());
}
@Test
public void givenValue_whenCreatesOption_thenCorrect() {
Option<Object> noneOption = Option.of(null);
Option<Object> someOption = Option.of("val");
assertEquals("None", noneOption.toString());
assertEquals("Some(val)", someOption.toString());
}
@Test
public void givenNull_whenCreatesOption_thenCorrect() {
String name = null;
Option<String> nameOption = Option.of(name);
assertEquals("baeldung", nameOption.getOrElse("baeldung"));
}
@Test
public void givenNonNull_whenCreatesOption_thenCorrect() {
String name = "baeldung";
Option<String> nameOption = Option.of(name);
assertEquals("baeldung", nameOption.getOrElse("notbaeldung"));
}
// try
@Test(expected = ArithmeticException.class)
public void givenBadCode_whenThrowsException_thenCorrect() {
int i = 1 / 0;
}
@Test
public void givenBadCode_whenTryHandles_thenCorrect() {
Try<Integer> result = Try.of(() -> 1 / 0);
assertTrue(result.isFailure());
}
@Test
public void givenBadCode_whenTryHandles_thenCorrect2() {
Try<Integer> result = Try.of(() -> 1 / 0);
int errorSentinel = result.getOrElse(-1);
assertEquals(-1, errorSentinel);
}
@Test(expected = RuntimeException.class)
public void givenBadCode_whenTryHandles_thenCorrect3() {
Try<Integer> result = Try.of(() -> 1 / 0);
result.getOrElseThrow(e->new RuntimeException(e));//re-throw different ex type
}
// lazy
@Test
public void givenFunction_whenEvaluatesWithLazy_thenCorrect() {
Lazy<Double> lazy = Lazy.of(Math::random);
assertFalse(lazy.isEvaluated());
double val1 = lazy.get();
assertTrue(lazy.isEvaluated());
double val2 = lazy.get();
assertEquals(val1, val2, 0.1);
}
// validation
@Test
public void whenValidationWorks_thenCorrect() {
PersonValidator personValidator = new PersonValidator();
Validation<Seq<String>, Person> valid = personValidator.validatePerson("John Doe", 30);
Validation<Seq<String>, Person> invalid = personValidator.validatePerson("John? Doe!4", -1);
assertEquals("Valid(Person [name=John Doe, age=30])", valid.toString());
assertEquals("Invalid(List(Invalid characters in name: ?!4, Age must be at least 0))", invalid.toString());
}
/*
* collections
*/
// list
@Test(expected = UnsupportedOperationException.class)
public void whenImmutableCollectionThrows_thenCorrect() {
java.util.List<String> wordList = Arrays.asList("abracadabra");
java.util.List<String> list = Collections.unmodifiableList(wordList);
list.add("boom");
}
@Test
public void whenSumsJava8List_thenCorrect() {
// Arrays.asList(1, 2, 3).stream().reduce((i, j) -> i + j);
int sum = IntStream.of(1, 2, 3)
.sum();
assertEquals(6, sum);
}
@Test
public void whenCreatesVavrList_thenCorrect() {
List<Integer> intList = List.of(1, 2, 3);
assertEquals(3, intList.length());
assertEquals(new Integer(1), intList.get(0));
assertEquals(new Integer(2), intList.get(1));
assertEquals(new Integer(3), intList.get(2));
}
@Test
public void whenSumsVavrList_thenCorrect() {
int sum = List.of(1, 2, 3)
.sum()
.intValue();
assertEquals(6, sum);
}
/*
* pattern matching
*/
@Test
public void whenIfWorksAsMatcher_thenCorrect() {
int input = 3;
String output;
if (input == 0) {
output = "zero";
}
if (input == 1) {
output = "one";
}
if (input == 2) {
output = "two";
}
if (input == 3) {
output = "three";
} else {
output = "unknown";
}
assertEquals("three", output);
}
@Test
public void whenSwitchWorksAsMatcher_thenCorrect() {
int input = 2;
String output;
switch (input) {
case 0:
output = "zero";
break;
case 1:
output = "one";
break;
case 2:
output = "two";
break;
case 3:
output = "three";
break;
default:
output = "unknown";
break;
}
assertEquals("two", output);
}
@Test
public void whenMatchworks_thenCorrect() {
int input = 2;
String output = Match(input).of(Case($(1), "one"), Case($(2), "two"), Case($(3), "three"), Case($(), "?"));
assertEquals("two", output);
}
}

View File

@@ -0,0 +1,364 @@
package com.baeldung.vavr.collections;
import io.vavr.Tuple;
import io.vavr.Tuple2;
import io.vavr.collection.*;
import io.vavr.collection.BitSet;
import io.vavr.collection.HashMap;
import io.vavr.collection.HashSet;
import io.vavr.collection.Iterator;
import io.vavr.collection.List;
import io.vavr.collection.Map;
import io.vavr.collection.Queue;
import io.vavr.collection.Set;
import io.vavr.collection.SortedMap;
import io.vavr.collection.SortedSet;
import io.vavr.collection.TreeMap;
import io.vavr.collection.TreeSet;
import io.vavr.collection.Vector;
import org.junit.Test;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
public class CollectionAPIUnitTest {
@Test
public void givenParams_whenListAPI_thenCorrect() {
List<String> list
= List.of("Java", "PHP", "Jquery", "JavaScript", "JShell", "JAVA");
List list1 = list.drop(2);
assertFalse(list1.contains("Java") && list1.contains("PHP"));
List list2 = list.dropRight(2);
assertFalse(list2.contains("JAVA") && list2.contains("JShell"));
List list3 = list.dropUntil(s -> s.contains("Shell"));
assertEquals(list3.size(), 2);
List list4 = list.dropWhile(s -> s.length() > 0);
assertTrue(list4.isEmpty());
List list5 = list.take(1);
assertEquals(list5.single(), "Java");
List list6 = list.takeRight(1);
assertEquals(list6.single(), "JAVA");
List list7 = list.takeUntil(s -> s.length() > 6);
assertEquals(list7.size(), 3);
List list8
= list.distinctBy( (s1, s2) -> s1.startsWith(s2.charAt(0)+"") ? 0 : 1);
assertEquals(list8.size(), 2);
Iterator<List<String>> iterator = list.grouped(2);
assertEquals(iterator.head().size(), 2);
Map<Boolean, List<String>> map = list.groupBy(e -> e.startsWith("J"));
assertEquals(map.size(), 2);
assertEquals(map.get(false).get().size(), 1);
assertEquals(map.get(true).get().size(), 5);
String words = List.of("Boys", "Girls")
.intersperse("and")
.reduce((s1, s2) -> s1.concat( " " + s2 ))
.trim();
assertEquals(words, "Boys and Girls");
}
@Test
public void givenEmptyList_whenStackAPI_thenCorrect() {
List<Integer> intList = List.empty();
List<Integer> intList1 = intList.pushAll(List.rangeClosed(5,10));
assertEquals(intList1.peek(), Integer.valueOf(10));
List intList2 = intList1.pop();
assertEquals(intList2.size(), (intList1.size() - 1) );
}
@Test
public void givenList_whenPrependTail_thenCorrect() {
List<Integer> intList = List.of(1, 2, 3);
List<Integer> newList = intList.tail()
.prepend(0);
assertEquals(new Integer(1), intList.get(0));
assertEquals(new Integer(2), intList.get(1));
assertEquals(new Integer(3), intList.get(2));
assertNotSame(intList.get(0), newList.get(0));
assertEquals(new Integer(0), newList.get(0));
assertSame(intList.get(1), newList.get(1));
assertSame(intList.get(2), newList.get(2));
}
@Test
public void givenQueue_whenEnqueued_thenCorrect() {
Queue<Integer> queue = Queue.of(1, 2, 3);
Queue<Integer> secondQueue = queue.enqueueAll(List.of(4,5));
assertEquals(3, queue.size());
assertEquals(5, secondQueue.size());
Tuple2<Integer, Queue<Integer>> result = secondQueue.dequeue();
assertEquals(Integer.valueOf(1), result._1);
Queue<Integer> tailQueue = result._2;
assertFalse(tailQueue.contains(secondQueue.get(0)));
Queue<Queue<Integer>> queue1 = queue.combinations(2);
assertEquals(queue1.get(2).toCharSeq(), CharSeq.of("23"));
}
@Test
public void givenStream_whenProcessed_thenCorrect() {
Stream<Integer> s1 = Stream.tabulate(5, (i)-> i + 1);
assertEquals(s1.get(2).intValue(), 3);
Stream<Integer> s = Stream.of(2,1,3,4);
Stream<Tuple2<Integer, Integer>> s2 = s.zip(List.of(7,8,9));
Tuple2<Integer, Integer> t1 = s2.get(0);
assertEquals(t1._1().intValue(), 2);
assertEquals(t1._2().intValue(), 7);
Stream<Integer> intStream = Stream.iterate(0, i -> i + 1)
.take(10);
assertEquals(10, intStream.size());
long evenSum = intStream.filter(i -> i % 2 == 0)
.sum()
.longValue();
assertEquals(20, evenSum);
}
@Test
public void givenArray_whenQueried_thenCorrect() {
Array<Integer> rArray = Array.range(1, 5);
assertFalse(rArray.contains(5));
Array<Integer> rArray2 = Array.rangeClosed(1, 5);
assertTrue(rArray2.contains(5));
Array<Integer> rArray3 = Array.rangeClosedBy(1,6,2);
assertEquals(rArray3.size(), 3);
Array<Integer> intArray = Array.of(1, 2, 3);
Array<Integer> newArray = intArray.removeAt(1);
assertEquals(2, newArray.size());
assertEquals(3, newArray.get(1).intValue());
Array<Integer> array2 = intArray.replace(1, 5);
assertEquals(array2.get(0).intValue(), 5);
}
@Test
public void givenVector_whenQueried_thenCorrect() {
Vector<Integer> intVector = Vector.range(1, 5);
Vector<Integer> newVector = intVector.replace(2, 6);
assertEquals(4, intVector.size());
assertEquals(4, newVector.size());
assertEquals(2, intVector.get(1).intValue());
assertEquals(6, newVector.get(1).intValue());
}
@Test
public void givenCharSeq_whenProcessed_thenCorrect() {
CharSeq chars = CharSeq.of("vavr");
CharSeq newChars = chars.replace('v', 'V');
assertEquals(4, chars.size());
assertEquals(4, newChars.size());
assertEquals('v', chars.charAt(0));
assertEquals('V', newChars.charAt(0));
assertEquals("Vavr", newChars.mkString());
}
@Test
public void givenHashSet_whenModified_thenCorrect() {
HashSet<String> set = HashSet.of("Red", "Green", "Blue");
HashSet<String> newSet = set.add("Yellow");
assertEquals(3, set.size());
assertEquals(4, newSet.size());
assertTrue(newSet.contains("Yellow"));
HashSet<Integer> set0 = HashSet.rangeClosed(1,5);
HashSet<Integer> set1 = HashSet.rangeClosed(3, 6);
assertEquals(set0.union(set1), HashSet.rangeClosed(1,6));
assertEquals(set0.diff(set1), HashSet.rangeClosed(1,2));
assertEquals(set0.intersect(set1), HashSet.rangeClosed(3,5));
}
@Test
public void givenSortedSet_whenIterated_thenCorrect() {
SortedSet<String> set = TreeSet.of("Red", "Green", "Blue");
assertEquals("Blue", set.head());
SortedSet<Integer> intSet = TreeSet.of(1,2,3);
assertEquals(2, intSet.average().get().intValue());
}
@Test
public void givenSortedSet_whenReversed_thenCorrect() {
SortedSet<String> reversedSet
= TreeSet.of(Comparator.reverseOrder(), "Green", "Red", "Blue");
assertEquals("Red", reversedSet.head());
String str = reversedSet.mkString(" and ");
assertEquals("Red and Green and Blue", str);
}
@Test
public void giveBitSet_whenApiMethods_thenCorrect() {
BitSet<Integer> bitSet = BitSet.of(1,2,3,4,5,6,7,8);
BitSet<Integer> bitSet1 = bitSet.takeUntil(i -> i > 4);
assertEquals(bitSet1.size(), 4);
}
@Test
public void givenMap_whenMapApi_thenCorrect() {
Map<Integer, List<Integer>> map = List.rangeClosed(0, 10)
.groupBy(i -> i % 2);
assertEquals(2, map.size());
assertEquals(6, map.get(0).get().size());
assertEquals(5, map.get(1).get().size());
Map<String, String> map1
= HashMap.of("key1", "val1", "key2", "val2", "key3", "val3");
Map<String, String> fMap
= map1.filterKeys(k -> k.contains("1") || k.contains("2"));
assertFalse(fMap.containsKey("key3"));
Map<String, String> fMap2
= map1.filterValues(v -> v.contains("3"));
assertEquals(fMap2.size(), 1);
assertTrue(fMap2.containsValue("val3"));
Map<String, Integer> map2 = map1.map(
(k, v) -> Tuple.of(k, Integer.valueOf(v.charAt(v.length() - 1) + "") ));
assertEquals(map2.get("key1").get().intValue(), 1);
}
@Test
public void givenTreeMap_whenIterated_thenCorrect() {
SortedMap<Integer, String> map
= TreeMap.of(3, "Three", 2, "Two", 4, "Four", 1, "One");
assertEquals(1, map.keySet().toJavaArray()[0]);
assertEquals("Four", map.get(4).get());
TreeMap<Integer, String> treeMap2 =
TreeMap.of(Comparator.reverseOrder(), 3,"three", 6, "six", 1, "one");
assertEquals(treeMap2.keySet().mkString(), "631");
}
@Test
public void givenJavaList_whenConverted_thenCorrect() {
java.util.List<Integer> javaList = java.util.Arrays.asList(1, 2, 3, 4);
List<Integer> vavrList = List.ofAll(javaList);
assertEquals(4, vavrList.size());
assertEquals(1, vavrList.head().intValue());
java.util.stream.Stream<Integer> javaStream = javaList.stream();
Set<Integer> vavrSet = HashSet.ofAll(javaStream);
assertEquals(4, vavrSet.size());
assertEquals(2, vavrSet.tail().head().intValue());
}
@Test
public void givenJavaStream_whenCollected_thenCorrect() {
List<Integer> vavrList = IntStream.range(1, 10)
.boxed()
.filter(i -> i % 2 == 0)
.collect(List.collector());
assertEquals(4, vavrList.size());
assertEquals(2, vavrList.head().intValue());
}
@Test
public void givenVavrList_whenConverted_thenCorrect() {
Integer[] array = List.of(1, 2, 3)
.toJavaArray(Integer.class);
assertEquals(3, array.length);
java.util.Map<String, Integer> map = List.of("1", "2", "3")
.toJavaMap(i -> Tuple.of(i, Integer.valueOf(i)));
assertEquals(2, map.get("2").intValue());
}
@Test
public void givenVavrList_whenCollected_thenCorrect() {
java.util.Set<Integer> javaSet = List.of(1, 2, 3)
.collect(Collectors.toSet());
assertEquals(3, javaSet.size());
assertEquals(1, javaSet.toArray()[0]);
}
@Test
public void givenVavrList_whenConvertedView_thenCorrect() {
java.util.List<Integer> javaList = List.of(1, 2, 3)
.asJavaMutable();
javaList.add(4);
assertEquals(4, javaList.get(3).intValue());
}
@Test(expected = UnsupportedOperationException.class)
public void givenVavrList_whenConvertedView_thenException() {
java.util.List<Integer> javaList = List.of(1, 2, 3)
.asJava();
assertEquals(3, javaList.get(2).intValue());
javaList.add(4);
}
@Test
public void givenList_whenSquared_thenCorrect() {
List<Integer> vavrList = List.of(1, 2, 3);
Number sum = vavrList.map(i -> i * i)
.sum();
assertEquals(14L, sum);
}
}

View File

@@ -0,0 +1,107 @@
package com.baeldung.vavr.collections;
import static io.vavr.API.Array;
import static io.vavr.API.Failure;
import static io.vavr.API.List;
import static io.vavr.API.None;
import static io.vavr.API.Some;
import static io.vavr.API.Stream;
import static io.vavr.API.Success;
import static io.vavr.API.Tuple;
import static io.vavr.API.Vector;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import io.vavr.Tuple3;
import io.vavr.collection.Array;
import io.vavr.collection.List;
import io.vavr.collection.Stream;
import io.vavr.collection.Vector;
import io.vavr.control.Option;
import io.vavr.control.Try;
public class CollectionFactoryMethodsUnitTest {
@Test
public void givenANoneOptionElement_whenCreated_thenCorrect() {
Option<Integer> none = None();
assertFalse(none == null);
assertEquals(none, Option.none());
}
@Test
public void givenASomeOptionElement_whenCreated_thenCorrect() {
Option<Integer> some = Some(1);
assertFalse(some == null);
assertTrue(some.contains(1));
}
@Test
public void givenATupleElement_whenCreated_thenCorrect() {
Tuple3<Character, String, Integer> tuple = Tuple('a', "chain", 2);
assertTrue(tuple!=null);
assertEquals(tuple._1(), new Character('a'));
assertEquals(tuple._2(), "chain");
assertEquals(tuple._3().intValue(), 2);
}
@Test
public void givenASuccessObject_whenEvaluated_thenSuccess() {
Try<Integer> integer = Success(55);
assertEquals(integer.get().intValue(), 55);
}
@Test
public void givenAFailureObject_whenEvaluated_thenExceptionThrown() {
Try<Integer> failure = Failure(new Exception("Exception X encapsulated here"));
try {
Integer i = failure.get();// evaluate a failure raise the exception
System.out.println(i);// not executed
} catch (Exception e) {
assertEquals(e.getMessage(), "Exception X encapsulated here");
}
}
@Test
public void givenAList_whenCreated_thenCorrect() {
List<Integer> list = List(1, 2, 3, 4, 5);
assertEquals(list.size(), 5);
assertEquals(list.get(0).intValue(), 1);
}
@Test
public void givenAnEmptyList_whenCreated_thenCorrect() {
List<Integer> empty = List();
assertEquals(empty.size(), 0);
assertEquals(empty, List.empty());
}
@Test
public void givenAnArray_whenCreated_thenCorrect() {
Array<Integer> array = Array(1, 2, 3, 4, 5);
assertEquals(array.size(), 5);
assertEquals(array.get(0).intValue(), 1);
}
@Test
public void givenAStream_whenCreated_thenCorrect() {
Stream<Integer> stream = Stream(1, 2, 3, 4, 5);
assertEquals(stream.size(), 5);
assertEquals(stream.get(0).intValue(), 1);
}
@Test
public void givenAVector_whenCreated_thenCorrect() {
Vector<Integer> vector = Vector(1, 2, 3, 4, 5);
assertEquals(vector.size(), 5);
assertEquals(vector.get(0).intValue(), 1);
}
}

View File

@@ -0,0 +1,87 @@
package com.baeldung.vavr.exception.handling;
import io.vavr.API;
import io.vavr.CheckedFunction1;
import io.vavr.Value;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
public class VavrExceptionHandlingUnitTest {
private static final Logger LOG = LoggerFactory.getLogger(VavrExceptionHandlingUnitTest.class);
private List<Integer> integers;
private List<Integer> validIntegersOnly;
@Before
public void init() {
integers = Arrays.asList(3, 9, 7, 0, 10, 20);
validIntegersOnly = Arrays.asList(3, 9, 7, 5, 10, 20);
}
@Test
public void exceptionCausingMethod_UsingCheckedFunction_ThenSuccess() {
CheckedFunction1<Integer, Integer> fn = i -> readFromFile(i);
validIntegersOnly.stream().map(fn.unchecked()).forEach(i -> LOG.debug("{}", i));
}
@Test(expected = IOException.class)
public void exceptionCausingMethod_UsingCheckedFunction_ThenFailure() {
CheckedFunction1<Integer, Integer> fn = i -> readFromFile(i);
integers.stream().map(fn.unchecked()).forEach(i -> LOG.debug("{}", i));
}
@Test
public void exceptionCausingMethod_UsingAPI_ThenSuccess() {
validIntegersOnly.stream().map(API.unchecked(i -> readFromFile(i))).forEach(i -> LOG.debug("{}", i));
}
@Test(expected = IOException.class)
public void exceptionCausingMethod_UsingAPI_ThenFailure() {
integers.stream().map(API.unchecked(i -> readFromFile(i))).forEach(i -> LOG.debug("{}", i));
}
@Test
public void exceptionCausingMethod_UsingLift_ThenSuccess() {
validIntegersOnly.stream().map(CheckedFunction1.lift(i -> readFromFile(i)))
.map(i -> i.getOrElse(-1))
.forEach(i -> {
Assert.assertNotSame(-1, i);
LOG.debug("{}", i);
});
}
@Test
public void exceptionCausingMethod_UsingLift_ThenFailure() {
integers.stream()
.map(CheckedFunction1.lift(i -> readFromFile(i)))
.map(i -> i.getOrElse(-1))
.forEach(i -> LOG.debug("{}", i));
}
@Test
public void exceptionCausingMethod_UsingTry_ThenSuccess() {
integers.stream()
.map(CheckedFunction1.liftTry(VavrExceptionHandlingUnitTest::readFromFile))
.flatMap(Value::toJavaStream)
.forEach(i -> LOG.debug("{}", i));
}
private static Integer readFromFile(Integer i) throws IOException {
if (i == 0) {
throw new IOException(); // mock IOException
}
return i * i;
}
}

View File

@@ -0,0 +1,115 @@
package com.baeldung.vavr.exception.handling;
import com.baeldung.vavr.exception.handling.client.ClientException;
import com.baeldung.vavr.exception.handling.client.HttpClient;
import com.baeldung.vavr.exception.handling.client.Response;
import io.vavr.collection.Stream;
import io.vavr.control.Option;
import io.vavr.control.Try;
import org.junit.Test;
import static io.vavr.API.$;
import static io.vavr.API.Case;
import static io.vavr.API.Match;
import static io.vavr.Predicates.instanceOf;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
public class VavrTryUnitTest {
@Test
public void givenHttpClient_whenMakeACall_shouldReturnSuccess() {
//given
Integer defaultChainedResult = 1;
String id = "a";
HttpClient httpClient = () -> new Response(id);
//when
Try<Response> response = new VavrTry(httpClient).getResponse();
Integer chainedResult = response
.map(this::actionThatTakesResponse)
.getOrElse(defaultChainedResult);
Stream<String> stream = response.toStream().map(it -> it.id);
//then
assertTrue(!stream.isEmpty());
assertTrue(response.isSuccess());
response.onSuccess(r -> assertEquals(id, r.id));
response.andThen(r -> assertEquals(id, r.id));
assertNotEquals(defaultChainedResult, chainedResult);
}
@Test
public void givenHttpClientFailure_whenMakeACall_shouldReturnFailure() {
//given
Integer defaultChainedResult = 1;
HttpClient httpClient = () -> {
throw new ClientException("problem");
};
//when
Try<Response> response = new VavrTry(httpClient).getResponse();
Integer chainedResult = response
.map(this::actionThatTakesResponse)
.getOrElse(defaultChainedResult);
Option<Response> optionalResponse = response.toOption();
//then
assertTrue(optionalResponse.isEmpty());
assertTrue(response.isFailure());
response.onFailure(ex -> assertTrue(ex instanceof ClientException));
assertEquals(defaultChainedResult, chainedResult);
}
@Test
public void givenHttpClientThatFailure_whenMakeACall_shouldReturnFailureAndNotRecover() {
//given
Response defaultResponse = new Response("b");
HttpClient httpClient = () -> {
throw new RuntimeException("critical problem");
};
//when
Try<Response> recovered = new VavrTry(httpClient).getResponse()
.recover(r -> Match(r).of(
Case($(instanceOf(ClientException.class)), defaultResponse)
));
//then
assertTrue(recovered.isFailure());
// recovered.getOrElseThrow(throwable -> {
// throw new RuntimeException(throwable);
// });
}
@Test
public void givenHttpClientThatFailure_whenMakeACall_shouldReturnFailureAndRecover() {
//given
Response defaultResponse = new Response("b");
HttpClient httpClient = () -> {
throw new ClientException("non critical problem");
};
//when
Try<Response> recovered = new VavrTry(httpClient).getResponse()
.recover(r -> Match(r).of(
Case($(instanceOf(ClientException.class)), defaultResponse),
Case($(instanceOf(IllegalArgumentException.class)), defaultResponse)
));
//then
assertTrue(recovered.isSuccess());
}
public int actionThatTakesResponse(Response response) {
return response.id.hashCode();
}
public int actionThatTakesTryResponse(Try<Response> response, int defaultTransformation) {
return response.transform(responses -> response.map(it -> it.id.hashCode()).getOrElse(defaultTransformation));
}
}

View File

@@ -0,0 +1,189 @@
package com.baeldung.vavr.future;
import io.vavr.Tuple;
import io.vavr.concurrent.Future;
import io.vavr.control.Option;
import io.vavr.control.Try;
import org.junit.Test;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import static java.util.concurrent.Executors.newSingleThreadExecutor;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class FutureUnitTest {
private static final String error = "Failed to get underlying value.";
private static final String HELLO = "Welcome to Baeldung!";
@Test
public void whenChangeExecutorService_thenCorrect() {
String result = Future.of(newSingleThreadExecutor(), () -> HELLO)
.getOrElse(error);
assertThat(result)
.isEqualTo(HELLO);
}
@Test
public void whenAppendData_thenCorrect1() {
String result = Future.of(() -> HELLO)
.getOrElse(error);
assertThat(result)
.isEqualTo(HELLO);
}
@Test
public void whenAppendData_thenCorrect2() {
Future<String> resultFuture = Future.of(() -> HELLO)
.await();
Option<Try<String>> futureOption = resultFuture.getValue();
String result = futureOption.get().getOrElse(error);
assertThat(result)
.isEqualTo(HELLO);
}
@Test
public void whenAppendData_thenSuccess() {
String result = Future.of(() -> HELLO)
.onSuccess(finalResult -> System.out.println("Successfully Completed - Result: " + finalResult))
.onFailure(finalResult -> System.out.println("Failed - Result: " + finalResult))
.getOrElse(error);
assertThat(result)
.isEqualTo(HELLO);
}
@Test
public void whenTransform_thenCorrect() {
Future<Object> future = Future.of(() -> 5)
.transformValue(result -> Try.of(() -> HELLO + result.get()));
assertThat(future.get()).isEqualTo(HELLO + 5);
}
@Test
public void whenChainingCallbacks_thenCorrect() {
Future.of(() -> HELLO)
.andThen(r -> System.out.println("Completed - 1: " + r))
.andThen(r -> System.out.println("Completed - 2: " + r));
}
@Test
public void whenCallAwait_thenCorrect() {
Future<String> resultFuture = Future.of(() -> HELLO)
.await();
String result = resultFuture.getValue().get().getOrElse(error);
assertThat(result)
.isEqualTo(HELLO);
}
@Test
public void whenDivideByZero_thenGetThrowable1() {
Future<Integer> resultFuture = Future.of(() -> 10 / 0);
assertThatThrownBy(resultFuture::get)
.isInstanceOf(ArithmeticException.class);
}
@Test
public void whenDivideByZero_thenGetThrowable2() {
Future<Integer> resultFuture = Future.of(() -> 10 / 0)
.await();
assertThat(resultFuture.getCause().get().getMessage())
.isEqualTo("/ by zero");
}
@Test
public void whenDivideByZero_thenCorrect() {
Future<Integer> resultFuture = Future.of(() -> 10 / 0)
.await();
assertThat(resultFuture.isCompleted()).isTrue();
assertThat(resultFuture.isSuccess()).isFalse();
assertThat(resultFuture.isFailure()).isTrue();
}
@Test
public void whenAppendData_thenFutureNotEmpty() {
Future<String> resultFuture = Future.of(() -> HELLO)
.await();
assertThat(resultFuture.isEmpty())
.isFalse();
}
@Test
public void whenCallZip_thenCorrect() {
Future<String> f1 = Future.of(() -> "hello1");
Future<String> f2 = Future.of(() -> "hello2");
assertThat(f1.zip(f2).get())
.isEqualTo(Tuple.of("hello1", "hello2"));
}
@Test
public void whenConvertToCompletableFuture_thenCorrect() throws InterruptedException, ExecutionException {
CompletableFuture<String> convertedFuture = Future.of(() -> HELLO)
.toCompletableFuture();
assertThat(convertedFuture.get())
.isEqualTo(HELLO);
}
@Test
public void whenCallMap_thenCorrect() {
Future<String> futureResult = Future.of(() -> "from Baeldung")
.map(a -> "Hello " + a)
.await();
assertThat(futureResult.get())
.isEqualTo("Hello from Baeldung");
}
@Test
public void whenCallFlatMap_thenCorrect() {
Future<Object> futureMap = Future.of(() -> 1)
.flatMap((i) -> Future.of(() -> "Hello: " + i));
assertThat(futureMap.get()).isEqualTo("Hello: 1");
}
@Test
public void whenFutureFails_thenGetErrorMessage() {
Future<String> future = Future.of(() -> "Hello".substring(-1))
.recover(x -> "fallback value");
assertThat(future.get())
.isEqualTo("fallback value");
}
@Test
public void whenFutureFails_thenGetAnotherFuture() {
Future<String> future = Future.of(() -> "Hello".substring(-1))
.recoverWith(x -> Future.of(() -> "fallback value"));
assertThat(future.get())
.isEqualTo("fallback value");
}
@Test
public void whenBothFuturesFail_thenGetErrorMessage() {
Future<String> f1 = Future.of(() -> "Hello".substring(-1));
Future<String> f2 = Future.of(() -> "Hello".substring(-2));
Future<String> errorMessageFuture = f1.fallbackTo(f2);
Future<Throwable> errorMessage = errorMessageFuture.failed();
assertThat(
errorMessage.get().getMessage())
.isEqualTo("String index out of range: -1");
}
}

View File

@@ -0,0 +1,46 @@
package com.baeldung.vavr.repositories;
import com.baeldung.Application;
import com.baeldung.repositories.VavrUserRepository;
import com.baeldung.vavr.User;
import io.vavr.collection.Seq;
import io.vavr.control.Option;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class VavrRepositoryIntegrationTest {
@Autowired
private VavrUserRepository userRepository;
@Before
public void setup() {
User user1 = new User();
user1.setName("John");
User user2 = new User();
user2.setName("John");
userRepository.save(user1);
userRepository.save(user2);
}
@Test
public void whenAddUsers_thenGetUsers() {
Option<User> user = userRepository.findById(1L);
assertFalse(user.isEmpty());
assertTrue(user.get().getName().equals("John"));
Seq<User> users = userRepository.findByName("John");
assertEquals(2, users.size());
}
}

View File

@@ -0,0 +1,23 @@
package com.baeldung.vavrvalidation.validator;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.instanceOf;
import org.junit.Test;
import com.baeldung.vavrvalidation.validator.UserValidator;
import io.vavr.control.Validation.Invalid;
import io.vavr.control.Validation.Valid;
public class UserValidatorUnitTest {
@Test
public void givenValidUserParams_whenValidated_thenInstanceOfValid() {
UserValidator userValidator = new UserValidator();
assertThat(userValidator.validateUser("John", "john@domain.com"), instanceOf(Valid.class));
}
@Test
public void givenInvalidUserParams_whenValidated_thenInstanceOfInvalid() {
UserValidator userValidator = new UserValidator();
assertThat(userValidator.validateUser("John", "no-email"), instanceOf(Invalid.class));
}
}

View File

@@ -0,0 +1,68 @@
package com.baeldung.vavrvalidation.validator;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import com.baeldung.vavrvalidation.model.User;
import io.vavr.collection.Seq;
import io.vavr.control.Either.Right;
import io.vavr.control.Validation.Invalid;
import io.vavr.control.Validation.Valid;
public class ValidationUnitTest {
private static UserValidator userValidator;
@BeforeClass
public static void setUpUserValidatorInstance() {
userValidator = new UserValidator();
}
@AfterClass
public static void teardownUserValidatorInstance() {
userValidator = null;
}
@Test
public void givenInvalidUserParams_whenValidated_thenInvalidInstance() {
assertThat(userValidator.validateUser("John", "no-email"), instanceOf(Invalid.class));
}
@Test
public void givenValidUserParams_whenValidated_thenValidInstance() {
assertThat(userValidator.validateUser("John", "john@domain.com"), instanceOf(Valid.class));
}
@Test
public void givenInvalidUserParams_whenValidated_thenTrueWithIsInvalidMethod() {
assertTrue(userValidator.validateUser("John", "no-email").isInvalid());
}
@Test
public void givenValidUserParams_whenValidated_thenTrueWithIsValidMethod() {
assertTrue(userValidator.validateUser("John", "john@domain.com").isValid());
}
@Test
public void givenInValidUserParams_withGetErrorMethod_thenGetErrorMessages() {
assertEquals("Name contains invalid characters, Email must be a well-formed email address", userValidator.validateUser(" ", "no-email")
.getError().intersperse(", ").fold("", String::concat));
}
@Test
public void givenValidUserParams_withGetMethod_thenGetUserInstance() {
assertThat(userValidator.validateUser("John", "john@domain.com").get(), instanceOf(User.class));
}
@Test
public void givenValidUserParams_withtoEitherMethod_thenRightInstance() {
assertThat(userValidator.validateUser("John", "john@domain.com").toEither(), instanceOf(Right.class));
}
@Test
public void givenValidUserParams_withFoldMethodWithListlengthUserHashCode_thenEqualstoParamsLength() {
assertEquals(2, (int) userValidator.validateUser(" ", " ").fold(Seq::length, User::hashCode));
}
}