1. Introduction
Java 8 introduced the java.util.Optional class to represent a value that may or may not be present to avoid NullPointerException. Converting an Optional to a java.util.ArrayList can be useful in scenarios where we want to handle optional values as lists. For example, finding the sum from a list or transforming the data. In this example, I will demonstrate the Optional ArrayList conversion with the following examples.
- Convert
OptionaltoArrayListviaisPresent. - Convert
OptionaltoArrayListviaorElseandorElseGet. - Convert
OptionaltoArrayListviaStream. - Convert
OptionaltoArrayListviaStreamand find the sum of the items. - Convert
OptionaltoArrayListviaStreamand loop the items.
2. Setup
In this step, I will create a maven project with the Junit library.
pom.xml
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.zheng.demo</groupId> <artifactId>convert_optional_to_arraylist</artifactId> <version>0.0.1-SNAPSHOT</version> <build> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.1</version> <configuration> <release>17</release> </configuration> </plugin> </plugins> </build> <dependencies> <!-- junit 5 --> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-engine</artifactId> <version>5.5.2</version> <scope>test</scope> </dependency> </dependencies> </project>
3. Junit Test Class For Optional ArrayList Conversion
In this step, I will create a TestConvertOptionalToArrayList.java test class to show a few ways to convert an Optional to an ArrayList.
test_ifPresent– when theOptionalhas value, then add it toArrayListwith theoptional.ifPresentmethod.test_orElse– when theOptionalhas no value, then add the default value toArrayListviaoptional.orElse.test_orElseGet – when theOptionalhas no value, then add the default value toArrayListviaoptional.orElseGet.test_stream_getSum– convert theOptionaltoArrayListvia theStreamfunction and get the sum of the list itemstest_stream_loopItems-convert theOptionaltoArrayListvia theStreamfunction and loop the list items.test_stream_withData– convert a valuedOptionaltoArrayList.test_stream_withNoData– convert an emptyOptionaltoArrayList.
TestConvertOptionalToArrayList.java
package org.zheng.demo;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import org.junit.jupiter.api.Test;
public class TestConvertOptionalToArrayList {
private static final String A_STRING = "Hello, Mary!";
private static final String Z_STRING = "Default";
private Optional<List<Integer>> emptyIntegers = Optional.empty();
private Optional<String> emptyOptional = Optional.empty();
private Optional<List<Integer>> optionalIntegers = Optional.of(List.of(30, 60));
private Optional<String> optionalValue = Optional.of(A_STRING);
private Integer getSum(final List<Integer> values) {
return values.stream().mapToInt(Integer::intValue).sum();
}
private void loopItems(final List<Integer> values) {
values.stream().forEach((value) -> System.out.println("Value: " + value));
}
@Test
void test_ifPresent() {
List<String> arrayList = new ArrayList<>();
optionalValue.ifPresent(arrayList::add);
assertTrue(arrayList.contains(A_STRING));
}
@Test
void test_orElse() {
List<String> arrayList = new ArrayList<>();
arrayList.add(emptyOptional.orElse(Z_STRING));
assertTrue(arrayList.contains(Z_STRING));
}
@Test
void test_orElseGet() {
List<String> arrayList = new ArrayList<>();
arrayList.add(emptyOptional.orElseGet(() -> Z_STRING));
assertTrue(arrayList.contains(Z_STRING));
}
@Test
void test_stream_getSum() {
optionalIntegers.ifPresentOrElse(values -> loopItems(values), () -> System.out.println("No values present"));
System.out.println("Loop Item via List");
loopItems(optionalIntegers.stream().flatMap(List::stream).collect(Collectors.toList()));
System.out.println("Sum Items via List: "
+ getSum(optionalIntegers.stream().flatMap(List::stream).collect(Collectors.toList())));
}
@Test
void test_stream_loopItems() {
emptyIntegers.ifPresentOrElse(values -> loopItems(values), () -> System.out.println("No values present"));
loopItems(emptyIntegers.stream().flatMap(List::stream).collect(Collectors.toList()));
}
@Test
void test_stream_withData() {
List<String> arrayList = optionalValue.stream().collect(Collectors.toList());
assertTrue(arrayList.contains(A_STRING));
}
@Test
void test_stream_withNoData() {
List<String> arrayList = emptyOptional.stream().collect(Collectors.toList());
assertTrue(arrayList.isEmpty());
}
}
- Line 23, 27:
Streamfunction to get sum and loop items. - Line 33, 41, 49: Add the
Optionalvalue toArrayListviaifPresent,orElse,orElseGetmethods. - Line 56, 67: The
Optionalvalue isListitself, use it asArrayList. - Line 59, 69: Convert the
ArrayListofOptionaltoStreamand flat it toArrayList. - Line 74, 81: Convert
OptionaltoArrayListviaStream.
4. Demo Optional ArrayList Conversion
In this step, I will run the Junit tests and capture the output here.
TestConvertOptionalToArrayList Output
Value: 30 Value: 60 Loop Item via List Value: 30 Value: 60 Sum Items via List: 90 No values present
Also capture the screenshot of the Junit test result.
5. Conclusion
In this example, I demonstrated the Optional ArrayList conversion with the examples
- Convert
OptionaltoArrayListviaisPresent. - Convert
OptionaltoArrayListviaorElseandorElseGet. - Convert
OptionaltoArrayListviaStream. - Convert
OptionaltoArrayListviaStreamand find the sum of the items. - Convert
OptionaltoArrayListviaStreamand loop the items.
6. Download
This was an example of a maven project which converting an Optional to an ArrayList.
You can download the full source code of this example here: Convert Optional to ArrayList
Thank you!
We will contact you soon.

This site uses Akismet to reduce spam. Learn how your comment data is processed.