Created
July 25, 2014 13:00
-
-
Save curtisallen/ec1946b4f453b5eb7e4e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Arrays; | |
import java.util.Objects; | |
import java.util.Optional; | |
import java.util.stream.Stream; | |
/** | |
* Utilities for working with default values | |
*/ | |
public class DefaultUtils { | |
/** | |
* Given objects that may be null return the first object that isn't null | |
* @param objects varargs of objects that may be null. The first object that | |
* isn't null will be returned. The last in the varargs is a | |
* default, if it's null a NullPointerException will be thrown | |
* @param <T> | |
* @return first non null object | |
*/ | |
public static <T> T defaultIfNull(final T... objects){ | |
Objects.requireNonNull(objects[objects.length -1], "default value cannot be null"); | |
Stream<T> objectStream = Arrays.asList(objects).stream(); | |
Optional<Optional<T>> condition = objectStream.map(Optional::ofNullable) | |
.filter(Optional::isPresent) | |
.findFirst(); | |
return condition.get().get(); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.junit.Test; | |
import static org.junit.Assert.*; | |
public class DefaultUtilsTest { | |
@Test | |
public void testDefaultUtils() throws Exception { | |
String defaultValue = DefaultUtils.defaultIfNull(null, "second value"); | |
assertEquals("second value", defaultValue); | |
defaultValue = DefaultUtils.defaultIfNull(null, null, null, null, "last value"); | |
assertEquals("last value", defaultValue); | |
defaultValue = DefaultUtils.defaultIfNull("first value", "second value"); | |
assertEquals("first value", defaultValue); | |
int defaultNumberValue = DefaultUtils.defaultIfNull(1, 2, 3, 4, 5, 6); | |
assertEquals(1, defaultNumberValue); | |
defaultNumberValue = DefaultUtils.defaultIfNull(null, null, null, 4, null, 5); | |
assertEquals(4, defaultNumberValue); | |
} | |
@Test(expected = NullPointerException.class) | |
public void testException() { | |
int defaultNumber = DefaultUtils.defaultIfNull(1, null); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment