Created
April 7, 2021 09:07
-
-
Save VAlux/fb41f35a6d8c41413dd4c2fad932f8f0 to your computer and use it in GitHub Desktop.
Java nested data structure extractors
This file contains 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
/** | |
* Will extract nested property from value, if it is not null | |
* | |
* @param value source value | |
* @param extractor extractor function for getting desired nested property from value. | |
* @param <A> type of the source value | |
* @param <B> type of the target nested property | |
* @return target nested property from value or null. | |
*/ | |
public static <A, B> B getOrNull(A value, Function<A, B> extractor) { | |
if (value != null) { | |
return extractor.apply(value); | |
} | |
return null; | |
} | |
/** | |
* Will extract nested property from value, if all the values in the chain are not null | |
* | |
* @param value source value | |
* @param extractor1 extractor function for getting intermediate nested property. | |
* @param extractor2 extractor function for getting desired nested property from value. | |
* @param <A> type of the source value | |
* @param <B> type of the intermediate property | |
* @param <C> type of the target nested property | |
* @return target nested property from value or null. | |
*/ | |
public static <A, B, C> C getOrNull(A value, Function<A, B> extractor1, Function<B, C> extractor2) { | |
if (value != null) { | |
return getOrNull(extractor1.apply(value), extractor2); | |
} | |
return null; | |
} | |
/** | |
* Will extract nested property from value, if all the values in the chain are not null | |
* | |
* @param value source value | |
* @param extractor1 extractor function for getting next intermediate nested property. | |
* @param extractor2 extractor function for getting next intermediate nested property. | |
* @param extractor3 extractor function for getting desired nested property from value. | |
* @param <A> type of the source value | |
* @param <B> type of the intermediate property | |
* @param <C> type of the intermediate property | |
* @param <D> type of the target nested property | |
* @return target nested property from value or null. | |
*/ | |
public static <A, B, C, D> D getOrNull(A value, | |
Function<A, B> extractor1, | |
Function<B, C> extractor2, | |
Function<C, D> extractor3) { | |
if (value != null) { | |
return getOrNull(extractor1.apply(value), extractor2, extractor3); | |
} | |
return null; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment