Skip to content

Instantly share code, notes, and snippets.

@varrix
Last active December 15, 2016 05:47
Show Gist options
  • Save varrix/14cdc08c96b8c5f5d08f to your computer and use it in GitHub Desktop.
Save varrix/14cdc08c96b8c5f5d08f to your computer and use it in GitHub Desktop.
/**
* Retrieve a UUID safely from a {@link String}.
*
* @param string The {@link String} to deserialize into an {@link UUID} object.
* @return {@link Optional#empty()} if the provided {@link String} is illegal, otherwise an {@link Optional}
* containing the deserialized {@link UUID} object.
*/
public static Optional<UUID> getUUID(String string) {
if (string.contains("-")) {
try {
return Optional.of(UUID.fromString(string));
} catch (IllegalArgumentException exc) {
return Optional.empty();
}
}
String builder = string.substring(0, 8) + "-"
+ string.substring(8, 12) + "-"
+ string.substring(12, 16) + "-"
+ string.substring(16, 20) + "-"
+ string.substring(20, 32);
return Optional.of(UUID.fromString(builder));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment