“There can be only one”
Highlander is a Java micro-library for safely retrieving the only element from a source that may have zero, one or more elements. Supports:
See www.michael-snell.com/2015/03/there-can-be-only-one.html for the motivation behind this.
Basic usage of “only”:
List<String> list = asList("ONE", "TWO");
return only(list); // Will throw an exception as the list contains more than one entry
List<String> list = asList();
return only(list); // Will throw an exception as the list is empty
List<String> list = asList("ONE");
return only(list); // Will return the only entry
Basic usage of “optionalOnly”:
List<String> list = asList("ONE", "TWO");
return optionalOnly(list); // Will throw an exception as the list contains more than one entry
List<String> list = asList();
return optionalOnly(list); // Will return Optional.empty as the list is empty
List<String> list = asList("ONE");
return optionalOnly(list); // Will return an Optional containing the only entry
See the tests at https://github.com/snellm/highlander/blob/master/src/test/java/com/snell/michael/highlander/ for more usage examples.
Current version is 0.4 - beta quality code (API is subject to change).
Maven:
<dependency>
<groupId>com.snell.michael.highlander</groupId>
<artifactId>highlander</artifactId>
<version>0.4</version>
</dependency>