Sho SHIMIZU
Committed by Gerrit Code Review

Add utility method to convert an Optional to a Stream

Change-Id: Ibc77d9bd7fc5232af01abc9b590a62801f13d65f
......@@ -39,6 +39,7 @@ import java.util.Arrays;
import java.util.Collection;
import java.util.Dictionary;
import java.util.List;
import java.util.Optional;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
......@@ -583,6 +584,17 @@ public abstract class Tools {
return StreamSupport.stream(it.spliterator(), false);
}
/**
* Converts an optional to a stream.
*
* @param optional optional to convert
* @param <T> type of enclosed value
* @return optional as a stream
*/
public static <T> Stream<T> stream(Optional<T> optional) {
return optional.map(Stream::of).orElse(Stream.empty());
}
// Auxiliary path visitor for recursive directory structure copying.
private static class DirectoryCopier extends SimpleFileVisitor<Path> {
private Path src;
......
......@@ -18,8 +18,11 @@ package org.onlab.util;
import org.junit.Test;
import org.onlab.junit.TestTools;
import java.util.Optional;
import java.util.concurrent.ThreadFactory;
import java.util.stream.Stream;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.*;
import static org.onlab.junit.TestTools.assertAfter;
......@@ -73,4 +76,14 @@ public class ToolsTest {
assertAfter(100, () -> assertEquals("incorrect thread state", Thread.State.TERMINATED, t.getState()));
}
@Test
public void testOptionalStream() {
Stream<Object> empty = Tools.stream(Optional.empty());
assertThat(empty.count(), is(0L));
String value = "value";
Stream<String> stream = Tools.stream(Optional.of(value));
assertThat(stream.allMatch(value::equals), is(true));
}
}
......