Core Java

Convert Optional to ArrayList

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 Optional to ArrayList via isPresent.
  • Convert Optional to ArrayList via orElse and orElseGet.
  • Convert Optional to ArrayList via Stream.
  • Convert Optional to ArrayList via Stream and find the sum of the items.
  • Convert Optional to ArrayList via Stream and 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 the Optional has value, then add it to ArrayList with the optional.ifPresent method.
  • test_orElse – when the Optional has no value, then add the default value to ArrayList via optional.orElse.
  • test_orElseGet – when the Optional has no value, then add the default value to ArrayList via optional.orElseGet.
  • test_stream_getSum – convert the Optional to ArrayList via the Stream function and get the sum of the list items
  • test_stream_loopItems -convert the Optional to ArrayList via the Stream function and loop the list items.
  • test_stream_withData – convert a valued Optional to ArrayList .
  • test_stream_withNoData – convert an empty Optional to ArrayList .

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: Stream function to get sum and loop items.
  • Line 33, 41, 49: Add the Optional value to ArrayList via ifPresent, orElse, orElseGet methods.
  • Line 56, 67: The Optional value is List itself, use it as ArrayList .
  • Line 59, 69: Convert the ArrayList of Optional to Streamand flat it to ArrayList.
  • Line 74, 81: Convert Optional to ArrayList via Stream.

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.

Figure 1. Junit Test Result

5. Conclusion

In this example, I demonstrated the Optional ArrayList conversion with the examples

  • Convert Optional to ArrayList via isPresent.
  • Convert Optional to ArrayList via orElse and orElseGet.
  • Convert Optional to ArrayList via Stream.
  • Convert Optional to ArrayList via Stream and find the sum of the items.
  • Convert Optional to ArrayList via Stream and loop the items.

6. Download

This was an example of a maven project which converting an Optional to an ArrayList.

Download
You can download the full source code of this example here: Convert Optional to ArrayList

Mary Zheng

Mary graduated from the Mechanical Engineering department at ShangHai JiaoTong University. She also holds a Master degree in Computer Science from Webster University. During her studies she has been involved with a large number of projects ranging from programming and software engineering. She worked as a lead Software Engineer in the telecommunications sector where she led and worked with others to design, implement, and monitor the software solution.
Subscribe
Notify of
guest

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

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button