Skip to content

Commit

Permalink
Merged for javadoc
Browse files Browse the repository at this point in the history
  • Loading branch information
fluentfuture committed Jun 23, 2024
2 parents 9bba402 + ee8ac98 commit 69115c0
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
22 changes: 22 additions & 0 deletions mug/src/main/java/com/google/mu/util/stream/MoreStreams.java
Original file line number Diff line number Diff line change
Expand Up @@ -475,6 +475,28 @@ public static <T> Stream<T> whileNotNull(Supplier<? extends T> supplier) {
false);
}

/**
* Returns a Stream wrapping {@code element} if it's not null; otherwise empty.
*
* <p>Useful if you'll chain it with further {@code flatMap()}, {@code anyMatch()} etc. For
* example:
*
* <pre>{@code
* boolean hasKeyword =
* MoreStreams.ifNotNull(type.getAnnotation(MyAnnotation.class))
* .flatMap(annotation -> annotation.keywords().stream())
* .anyMatch(currentKeyword::equals);
* }</pre>
*
* <p>It's the Stream counterpart of {@link java.util.Optional#ofNullable}, and is more concise
* and efficient than {@code Optional.ofNullable(element).stream()}.
*
* @since 8.1
*/
public static <T> Stream<T> ifNotNull(T element) {
return element == null ? Stream.empty() : Stream.of(element);
}

/**
* Returns a sequential stream with {@code sideEfect} attached on every element.
*
Expand Down
12 changes: 11 additions & 1 deletion mug/src/test/java/com/google/mu/util/stream/MoreStreamsTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -346,7 +346,7 @@ public class MoreStreamsTest {
@Test public void testNulls() throws Exception {
NullPointerTester tester = new NullPointerTester();
asList(MoreStreams.class.getDeclaredMethods()).stream()
.filter(m -> m.getName().equals("generate"))
.filter(m -> m.getName().equals("generate") || m.getName().equals("ifNotNull"))
.forEach(tester::ignore);
tester.testAllPublicStaticMethods(MoreStreams.class);
}
Expand Down Expand Up @@ -387,4 +387,14 @@ public class MoreStreamsTest {
.containsExactly(10, 2L, 9, 3L, 8, 1L)
.inOrder();
}

@Test public void testIfNotNull_fromNull() {
Object element = null;
assertThat(MoreStreams.ifNotNull(element)).isEmpty();
}

@Test public void testIfNotNull_fromNonNull() {
Object element = 1;
assertThat(MoreStreams.ifNotNull(element)).containsExactly(1);
}
}

0 comments on commit 69115c0

Please sign in to comment.