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; ...@@ -39,6 +39,7 @@ import java.util.Arrays;
39 import java.util.Collection; 39 import java.util.Collection;
40 import java.util.Dictionary; 40 import java.util.Dictionary;
41 import java.util.List; 41 import java.util.List;
42 +import java.util.Optional;
42 import java.util.Random; 43 import java.util.Random;
43 import java.util.Set; 44 import java.util.Set;
44 import java.util.concurrent.CompletableFuture; 45 import java.util.concurrent.CompletableFuture;
...@@ -583,6 +584,17 @@ public abstract class Tools { ...@@ -583,6 +584,17 @@ public abstract class Tools {
583 return StreamSupport.stream(it.spliterator(), false); 584 return StreamSupport.stream(it.spliterator(), false);
584 } 585 }
585 586
587 + /**
588 + * Converts an optional to a stream.
589 + *
590 + * @param optional optional to convert
591 + * @param <T> type of enclosed value
592 + * @return optional as a stream
593 + */
594 + public static <T> Stream<T> stream(Optional<T> optional) {
595 + return optional.map(Stream::of).orElse(Stream.empty());
596 + }
597 +
586 // Auxiliary path visitor for recursive directory structure copying. 598 // Auxiliary path visitor for recursive directory structure copying.
587 private static class DirectoryCopier extends SimpleFileVisitor<Path> { 599 private static class DirectoryCopier extends SimpleFileVisitor<Path> {
588 private Path src; 600 private Path src;
......
...@@ -18,8 +18,11 @@ package org.onlab.util; ...@@ -18,8 +18,11 @@ package org.onlab.util;
18 import org.junit.Test; 18 import org.junit.Test;
19 import org.onlab.junit.TestTools; 19 import org.onlab.junit.TestTools;
20 20
21 +import java.util.Optional;
21 import java.util.concurrent.ThreadFactory; 22 import java.util.concurrent.ThreadFactory;
23 +import java.util.stream.Stream;
22 24
25 +import static org.hamcrest.Matchers.is;
23 import static org.junit.Assert.*; 26 import static org.junit.Assert.*;
24 import static org.onlab.junit.TestTools.assertAfter; 27 import static org.onlab.junit.TestTools.assertAfter;
25 28
...@@ -73,4 +76,14 @@ public class ToolsTest { ...@@ -73,4 +76,14 @@ public class ToolsTest {
73 assertAfter(100, () -> assertEquals("incorrect thread state", Thread.State.TERMINATED, t.getState())); 76 assertAfter(100, () -> assertEquals("incorrect thread state", Thread.State.TERMINATED, t.getState()));
74 } 77 }
75 78
79 + @Test
80 + public void testOptionalStream() {
81 + Stream<Object> empty = Tools.stream(Optional.empty());
82 + assertThat(empty.count(), is(0L));
83 +
84 + String value = "value";
85 + Stream<String> stream = Tools.stream(Optional.of(value));
86 + assertThat(stream.allMatch(value::equals), is(true));
87 + }
88 +
76 } 89 }
......