[BAEL-16531] - Move all the existing articles on "optional" under java-optional

This commit is contained in:
catalin-burcea 2019-11-26 12:01:07 +02:00
parent 9f25b72ca4
commit 166723cf62
29 changed files with 230 additions and 201 deletions

View File

@ -12,4 +12,3 @@ This module contains articles about Java 11 core features
- [An Introduction to Epsilon GC: A No-Op Experimental Garbage Collector](https://www.baeldung.com/jvm-epsilon-gc-garbage-collector)
- [Guide to jlink](https://www.baeldung.com/jlink)
- [Negate a Predicate Method Reference with Java 11](https://www.baeldung.com/java-negate-predicate-method-reference)
- [Transforming an Empty String into an Empty Optional](https://www.baeldung.com/java-empty-string-to-empty-optional)

View File

@ -5,14 +5,14 @@
version="2.0">
<persistence-unit
name="com.baeldung.optionalReturnType"
name="com.baeldung.optionalreturntype"
transaction-type="RESOURCE_LOCAL">
<description>Persist Optional Return Type Demo</description>
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>com.baeldung.optionalReturnType.User</class>
<class>com.baeldung.optionalReturnType.UserOptional</class>
<class>com.baeldung.optionalreturntype.User</class>
<class>com.baeldung.optionalreturntype.UserOptional</class>
<!--
<class>com.baeldung.optionalReturnType.UserOptionalField</class>
<class>com.baeldung.optionalreturntype.UserOptionalField</class>
-->
<exclude-unlisted-classes>true</exclude-unlisted-classes>

View File

@ -5,7 +5,6 @@ This module contains articles about the improvements to core Java features intro
### Relevant Articles:
- [New Stream Collectors in Java 9](http://www.baeldung.com/java9-stream-collectors)
- [Java 9 Optional API Additions](https://www.baeldung.com/java-9-optional)
- [Java 9 Convenience Factory Methods for Collections](https://www.baeldung.com/java-9-collections-factory-methods)
- [Java 9 Stream API Improvements](https://www.baeldung.com/java-9-stream-api)
- [Java 9 java.util.Objects Additions](https://www.baeldung.com/java-9-objects-new)

View File

@ -1,85 +0,0 @@
package com.baeldung.java9;
public class Java9OptionalTest {
@Test
public void givenOptionalOfSome_whenToStream_thenShouldTreatItAsOneElementStream() {
//given
Optional<String> value = Optional.of("a");
//when
List<String> collect = value.stream().map(String::toUpperCase).collect(Collectors.toList());
//then
assertThat(collect).hasSameElementsAs(List.of("A"));
}
@Test
public void givenOptionalOfNone_whenToStream_thenShouldTreatItAsZeroElementStream() {
//given
Optional<String> value = Optional.empty();
//when
List<String> collect = value.stream().map(String::toUpperCase).collect(Collectors.toList());
//then
assertThat(collect).isEmpty();
}
@Test
public void givenOptional_whenPresent_thenShouldExecuteProperCallback() {
//given
Optional<String> value = Optional.of("properValue");
AtomicInteger successCounter = new AtomicInteger(0);
AtomicInteger onEmptyOptionalCounter = new AtomicInteger(0);
//when
value.ifPresentOrElse((v) -> successCounter.incrementAndGet(), onEmptyOptionalCounter::incrementAndGet);
//then
assertThat(successCounter.get()).isEqualTo(1);
assertThat(onEmptyOptionalCounter.get()).isEqualTo(0);
}
@Test
public void givenOptional_whenNotPresent_thenShouldExecuteProperCallback() {
//given
Optional<String> value = Optional.empty();
AtomicInteger successCounter = new AtomicInteger(0);
AtomicInteger onEmptyOptionalCounter = new AtomicInteger(0);
//when
value.ifPresentOrElse((v) -> successCounter.incrementAndGet(), onEmptyOptionalCounter::incrementAndGet);
//then
assertThat(successCounter.get()).isEqualTo(0);
assertThat(onEmptyOptionalCounter.get()).isEqualTo(1);
}
@Test
public void givenOptional_whenPresent_thenShouldTakeAValueFromIt() {
//given
String expected = "properValue";
Optional<String> value = Optional.of(expected);
Optional<String> defaultValue = Optional.of("default");
//when
Optional<String> result = value.or(() -> defaultValue);
//then
assertThat(result.get()).isEqualTo(expected);
}
@Test
public void givenOptional_whenEmpty_thenShouldTakeAValueFromOr() {
//given
String defaultString = "default";
Optional<String> value = Optional.empty();
Optional<String> defaultValue = Optional.of(defaultString);
//when
Optional<String> result = value.or(() -> defaultValue);
//then
assertThat(result.get()).isEqualTo(defaultString);
}
}

View File

@ -4,13 +4,11 @@ This module contains articles about Java 9 core features
### Relevant Articles:
- [Method Handles in Java](http://www.baeldung.com/java-method-handles)
- [Introduction to Chronicle Queue](http://www.baeldung.com/java-chronicle-queue)
- [Optional orElse Optional](http://www.baeldung.com/java-optional-or-else-optional)
- [Method Handles in Java](https://www.baeldung.com/java-method-handles)
- [Introduction to Chronicle Queue](https://www.baeldung.com/java-chronicle-queue)
- [Iterate Through a Range of Dates in Java](https://www.baeldung.com/java-iterate-date-range)
- [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap)
- [Immutable Set in Java](https://www.baeldung.com/java-immutable-set)
- [Filtering a Stream of Optionals in Java](https://www.baeldung.com/java-filter-stream-of-optional)
Note: also contains part of the code for the article
[How to Filter a Collection in Java](https://www.baeldung.com/java-collection-filtering).

View File

@ -1,51 +0,0 @@
package com.baeldung.optionals;
import static org.junit.Assert.assertEquals;
import java.util.Optional;
import org.junit.Test;
public class OptionalsTest {
@Test
public void givenOptional_whenEmptyValue_thenCustomMessage() {
assertEquals(Optional.of("Name not provided"), Optionals.getName(Optional.ofNullable(null)));
}
@Test
public void givenOptional_whenValue_thenOptional() {
String name = "Filan Fisteku";
Optional<String> optionalString = Optional.ofNullable(name);
assertEquals(optionalString, Optionals.getName(optionalString));
}
@Test
public void givenOptional_whenValue_thenOptionalGeneralMethod() {
String name = "Filan Fisteku";
String missingOptional = "Name not provided";
Optional<String> optionalString = Optional.ofNullable(name);
Optional<String> fallbackOptionalString = Optional.ofNullable(missingOptional);
assertEquals(optionalString, Optionals.or(optionalString, fallbackOptionalString));
}
@Test
public void givenEmptyOptional_whenValue_thenOptionalGeneralMethod() {
String missingOptional = "Name not provided";
Optional<String> optionalString = Optional.empty();
Optional<String> fallbackOptionalString = Optional.ofNullable(missingOptional);
assertEquals(fallbackOptionalString, Optionals.or(optionalString, fallbackOptionalString));
}
@Test
public void givenGuavaOptional_whenInvoke_thenOptional() {
String name = "Filan Fisteku";
com.google.common.base.Optional<String> stringOptional = com.google.common.base.Optional.of(name);
assertEquals(stringOptional, Optionals.getOptionalGuavaName(stringOptional));
}
@Test
public void givenGuavaOptional_whenNull_thenDefaultText() {
assertEquals(com.google.common.base.Optional.of("Name not provided"), Optionals.getOptionalGuavaName(com.google.common.base.Optional.fromNullable(null)));
}
}

View File

@ -15,6 +15,5 @@ This module contains articles about core java exceptions
- [Java Try with Resources](https://www.baeldung.com/java-try-with-resources)
- [Java Global Exception Handler](https://www.baeldung.com/java-global-exception-handler)
- [Common Java Exceptions](https://www.baeldung.com/java-common-exceptions)
- [Throw Exception in Optional in Java 8](https://www.baeldung.com/java-optional-throw-exception)
- [How to Find an Exceptions Root Cause in Java](https://www.baeldung.com/java-exception-root-cause)
- [Is It a Bad Practice to Catch Throwable?](https://www.baeldung.com/java-catch-throwable-bad-practice)

View File

@ -1,8 +1,13 @@
=========
## Java Optional
## Core Java Optional
This module contains articles about Java Optional.
### Relevant Articles:
- [Java Optional as Return Type](https://www.baeldung.com/java-optional-return)
- [Guide To Java 8 Optional](https://www.baeldung.com/java-optional)
- [Java Optional orElse() vs orElseGet()](https://www.baeldung.com/java-optional-or-else-vs-or-else-get)
- [Guide to Java 8 Optional](https://www.baeldung.com/java-optional)
- [Java Optional orElse() vs orElseGet()](https://www.baeldung.com/java-optional-or-else-vs-or-else-get)
- [Transforming an Empty String into an Empty Optional](https://www.baeldung.com/java-empty-string-to-empty-optional)
- [Filtering a Stream of Optionals in Java](https://www.baeldung.com/java-filter-stream-of-optional)
- [Java 9 Optional API Additions](https://www.baeldung.com/java-9-optional)
- [Throw Exception in Optional in Java 8](https://www.baeldung.com/java-optional-throw-exception)
- [Optional orElse Optional](https://www.baeldung.com/java-optional-or-else-optional)

View File

@ -42,11 +42,31 @@
<artifactId>jmh-generator-bytecode</artifactId>
<version>${jmh-generator.version}</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>json-path</artifactId>
<version>${rest-assured.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<hibernate.core.version>5.4.0.Final</hibernate.core.version>
<jmh-core.version>1.19</jmh-core.version>
<jmh-generator.version>1.19</jmh-generator.version>
<guava.version>27.1-jre</guava.version>
<assertj.version>3.10.0</assertj.version>
<rest-assured.version>3.1.1</rest-assured.version>
</properties>
</project>

View File

@ -1,4 +1,4 @@
package com.baeldung.optional;
package com.baeldung.optional.orelse;
import java.util.Arrays;
import java.util.List;

View File

@ -1,4 +1,4 @@
package com.baeldung.optional;
package com.baeldung.optional.orelse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

View File

@ -1,4 +1,4 @@
package com.baeldung.optionalReturnType;
package com.baeldung.optionalreturntype;
import java.util.HashMap;
import java.util.Map;

View File

@ -1,4 +1,4 @@
package com.baeldung.optionalReturnType;
package com.baeldung.optionalreturntype;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

View File

@ -1,4 +1,4 @@
package com.baeldung.optionalReturnType;
package com.baeldung.optionalreturntype;
import java.util.Optional;
@ -7,13 +7,13 @@ import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class PersistOptionalTypeExample {
static String persistenceUnit = "com.baeldung.optionalReturnType";
static String persistenceUnit = "com.baeldung.optionalreturntype";
static EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnit);
static EntityManager entityManager = emf.createEntityManager();
// to run this app, uncomment the follow line in META-INF/persistence.xml
// <class>com.baeldung.optionalReturnType.UserOptionalField</class>
// <class>com.baeldung.optionalreturntype.UserOptionalField</class>
public static void main(String[] args) {
UserOptionalField user1 = new UserOptionalField();
user1.setUserId(1l);

View File

@ -1,11 +1,11 @@
package com.baeldung.optionalReturnType;
package com.baeldung.optionalreturntype;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class PersistOptionalTypeExample2 {
static String persistenceUnit = "com.baeldung.optionalReturnType";
static String persistenceUnit = "com.baeldung.optionalreturntype";
static EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnit);
static EntityManager em = emf.createEntityManager();

View File

@ -1,11 +1,11 @@
package com.baeldung.optionalReturnType;
package com.baeldung.optionalreturntype;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class PersistUserExample {
static String persistenceUnit = "com.baeldung.optionalReturnType";
static String persistenceUnit = "com.baeldung.optionalreturntype";
static EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnit);
static EntityManager em = emf.createEntityManager();

View File

@ -1,4 +1,4 @@
package com.baeldung.optionalReturnType;
package com.baeldung.optionalreturntype;
import java.io.FileOutputStream;
import java.io.IOException;

View File

@ -1,4 +1,4 @@
package com.baeldung.optionalReturnType;
package com.baeldung.optionalreturntype;
import java.io.Serializable;

View File

@ -1,4 +1,4 @@
package com.baeldung.optionalReturnType;
package com.baeldung.optionalreturntype;
import java.io.Serializable;
import java.util.Optional;

View File

@ -1,4 +1,4 @@
package com.baeldung.optionalReturnType;
package com.baeldung.optionalreturntype;
import java.io.Serializable;
import java.util.Optional;

View File

@ -1,20 +1,20 @@
package com.baeldung.optionals;
package com.baeldung.orelseoptional;
import java.util.Optional;
public class Optionals {
public class OptionalUtils {
public static <T> Optional<T> or(Optional<T> optional, Optional<T> fallback) {
return optional.isPresent() ? optional : fallback;
}
public static Optional<String> getName(Optional<String> name) {
return name.or(() -> getCustomMessage());
}
public static com.google.common.base.Optional<String> getOptionalGuavaName(com.google.common.base.Optional<String> name) {
return name.or(getCustomMessageGuava());
}
// public static Optional<String> getName(Optional<String> name) {
// return name.or(() -> getCustomMessage());
// }
//
// public static com.google.common.base.Optional<String> getOptionalGuavaName(com.google.common.base.Optional<String> name) {
// return name.or(getCustomMessageGuava());
// }
private static Optional<String> getCustomMessage() {
return Optional.of("Name not provided");

View File

@ -1,4 +1,4 @@
package com.baeldung;
package com.baeldung.emptystringoptional;
import com.google.common.base.Strings;
import org.junit.Assert;
@ -16,12 +16,13 @@ public class EmptyStringToEmptyOptionalUnitTest {
Assert.assertFalse(opt.isPresent());
}
@Test
public void givenEmptyString_whenFilteringOnOptionalInJava11_thenEmptyOptionalIsReturned() {
String str = "";
Optional<String> opt = Optional.ofNullable(str).filter(Predicate.not(String::isEmpty));
Assert.assertFalse(opt.isPresent());
}
// Uncomment code when code base is compatible with Java 11
// @Test
// public void givenEmptyString_whenFilteringOnOptionalInJava11_thenEmptyOptionalIsReturned() {
// String str = "";
// Optional<String> opt = Optional.ofNullable(str).filter(Predicate.not(String::isEmpty));
// Assert.assertFalse(opt.isPresent());
// }
@Test
public void givenEmptyString_whenPassingResultOfEmptyToNullToOfNullable_thenEmptyOptionalIsReturned() {

View File

@ -1,4 +1,4 @@
package com.baeldung.java9;
package com.baeldung.filterstream;
import static org.junit.Assert.assertEquals;
@ -47,15 +47,17 @@ public class Java9OptionalsStreamUnitTest {
assertEquals("bar", filteredList.get(1));
}
@Test
public void filterOutPresentOptionalsWithJava9() {
assertEquals(4, listOfOptionals.size());
List<String> filteredList = listOfOptionals.stream().flatMap(Optional::stream).collect(Collectors.toList());
assertEquals(2, filteredList.size());
assertEquals("foo", filteredList.get(0));
assertEquals("bar", filteredList.get(1));
}
// Uncomment code when code base is compatible with Java 9
// @Test
// public void filterOutPresentOptionalsWithJava9() {
// assertEquals(4, listOfOptionals.size());
//
// List<String> filteredList = listOfOptionals.stream().flatMap(Optional::stream).collect(Collectors.toList());
//
// assertEquals(2, filteredList.size());
// assertEquals("foo", filteredList.get(0));
// assertEquals("bar", filteredList.get(1));
// }
}

View File

@ -0,0 +1,95 @@
package com.baeldung.java9additions;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
// Uncomment code when code base is compatible with Java 9
//public class Java9OptionalUnitTest {
//
// @Test
// public void givenOptionalOfSome_whenToStream_thenShouldTreatItAsOneElementStream() {
// //given
// Optional<String> value = Optional.of("a");
//
// //when
// List<String> collect = value.stream().map(String::toUpperCase).collect(Collectors.toList());
//
// //then
// assertThat(collect).hasSameElementsAs(List.of("A"));
// }
//
// @Test
// public void givenOptionalOfNone_whenToStream_thenShouldTreatItAsZeroElementStream() {
// //given
// Optional<String> value = Optional.empty();
//
// //when
// List<String> collect = value.stream().map(String::toUpperCase).collect(Collectors.toList());
//
// //then
// assertThat(collect).isEmpty();
// }
//
// @Test
// public void givenOptional_whenPresent_thenShouldExecuteProperCallback() {
// //given
// Optional<String> value = Optional.of("properValue");
// AtomicInteger successCounter = new AtomicInteger(0);
// AtomicInteger onEmptyOptionalCounter = new AtomicInteger(0);
//
// //when
// value.ifPresentOrElse((v) -> successCounter.incrementAndGet(), onEmptyOptionalCounter::incrementAndGet);
//
// //then
// assertThat(successCounter.get()).isEqualTo(1);
// assertThat(onEmptyOptionalCounter.get()).isEqualTo(0);
// }
//
// @Test
// public void givenOptional_whenNotPresent_thenShouldExecuteProperCallback() {
// //given
// Optional<String> value = Optional.empty();
// AtomicInteger successCounter = new AtomicInteger(0);
// AtomicInteger onEmptyOptionalCounter = new AtomicInteger(0);
//
// //when
// value.ifPresentOrElse((v) -> successCounter.incrementAndGet(), onEmptyOptionalCounter::incrementAndGet);
//
// //then
// assertThat(successCounter.get()).isEqualTo(0);
// assertThat(onEmptyOptionalCounter.get()).isEqualTo(1);
// }
//
// @Test
// public void givenOptional_whenPresent_thenShouldTakeAValueFromIt() {
// //given
// String expected = "properValue";
// Optional<String> value = Optional.of(expected);
// Optional<String> defaultValue = Optional.of("default");
//
// //when
// Optional<String> result = value.or(() -> defaultValue);
//
// //then
// assertThat(result.get()).isEqualTo(expected);
// }
//
// @Test
// public void givenOptional_whenEmpty_thenShouldTakeAValueFromOr() {
// //given
// String defaultString = "default";
// Optional<String> value = Optional.empty();
// Optional<String> defaultValue = Optional.of(defaultString);
//
// //when
// Optional<String> result = value.or(() -> defaultValue);
//
// //then
// assertThat(result.get()).isEqualTo(defaultString);
// }
//}

View File

@ -1,4 +1,4 @@
package com.baeldung.java8.optional;
package com.baeldung.optional;
import org.junit.Before;
import org.junit.Test;

View File

@ -1,7 +1,5 @@
package com.baeldung.java8.optional;
package com.baeldung.optional;
import com.baeldung.optional.Modem;
import com.baeldung.optional.Person;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -260,7 +258,7 @@ public class OptionalUnitTest {
return "Default Value";
}
// Uncomment code when code base is compatiable with Java 11
// Uncomment code when code base is compatible with Java 11
// @Test
// public void givenAnEmptyOptional_thenIsEmptyBehavesAsExpected() {
// Optional<String> opt = Optional.of("Baeldung");

View File

@ -1,4 +1,4 @@
package com.baeldung.java8.optional;
package com.baeldung.optional.orelse;
import org.junit.Test;
import org.slf4j.Logger;
@ -6,8 +6,6 @@ import org.slf4j.LoggerFactory;
import static org.junit.Assert.*;
import com.baeldung.optional.OrElseAndOrElseGet;
public class OrElseAndOrElseGetUnitTest {
private OrElseAndOrElseGet orElsevsOrElseGet = new OrElseAndOrElseGet();

View File

@ -0,0 +1,52 @@
package com.baeldung.orelseoptional;
import static org.junit.Assert.assertEquals;
import java.util.Optional;
import org.junit.Test;
public class OrElseOptionalUnitTest {
@Test
public void givenOptional_whenValue_thenOptionalGeneralMethod() {
String name = "Filan Fisteku";
String missingOptional = "Name not provided";
Optional<String> optionalString = Optional.ofNullable(name);
Optional<String> fallbackOptionalString = Optional.ofNullable(missingOptional);
assertEquals(optionalString, OptionalUtils.or(optionalString, fallbackOptionalString));
}
@Test
public void givenEmptyOptional_whenValue_thenOptionalGeneralMethod() {
String missingOptional = "Name not provided";
Optional<String> optionalString = Optional.empty();
Optional<String> fallbackOptionalString = Optional.ofNullable(missingOptional);
assertEquals(fallbackOptionalString, OptionalUtils.or(optionalString, fallbackOptionalString));
}
// Uncomment code when code base is compatible with Java 9
// @Test
// public void givenOptional_whenEmptyValue_thenCustomMessage() {
// assertEquals(Optional.of("Name not provided"), OptionalUtils.getName(Optional.ofNullable(null)));
// }
//
// @Test
// public void givenOptional_whenValue_thenOptional() {
// String name = "Filan Fisteku";
// Optional<String> optionalString = Optional.ofNullable(name);
// assertEquals(optionalString, OptionalUtils.getName(optionalString));
// }
//
// @Test
// public void givenGuavaOptional_whenInvoke_thenOptional() {
// String name = "Filan Fisteku";
// com.google.common.base.Optional<String> stringOptional = com.google.common.base.Optional.of(name);
// assertEquals(stringOptional, OptionalUtils.getOptionalGuavaName(stringOptional));
// }
//
// @Test
// public void givenGuavaOptional_whenNull_thenDefaultText() {
// assertEquals(com.google.common.base.Optional.of("Name not provided"), OptionalUtils.getOptionalGuavaName(com.google.common.base.Optional.fromNullable(null)));
// }
}

View File

@ -23,7 +23,6 @@
- [Java Global Exception Handler](http://www.baeldung.com/java-global-exception-handler)
- [How to Get the Size of an Object in Java](http://www.baeldung.com/java-size-of-object)
- [Common Java Exceptions](http://www.baeldung.com/java-common-exceptions)
- [Throw Exception in Optional in Java 8](https://www.baeldung.com/java-optional-throw-exception)
- [Merging java.util.Properties Objects](https://www.baeldung.com/java-merging-properties)
- [Java Try with Resources](https://www.baeldung.com/java-try-with-resources)
- [Guide to Character Encoding](https://www.baeldung.com/java-char-encoding)