Add nullable getters for arrays and collections

This commit is contained in:
Roman Zhuravlev 2023-07-24 02:09:31 +05:00
parent cd7e3f6f69
commit 3c6c655ff2
2 changed files with 6 additions and 4 deletions

View file

@ -3,6 +3,7 @@ package org.zhdev.util;
import java.util.Collection; import java.util.Collection;
import java.util.function.Function; import java.util.function.Function;
import java.util.function.IntFunction; import java.util.function.IntFunction;
import java.util.function.Supplier;
public class ArrayUtils { public class ArrayUtils {
public static <T> T get(T[] array, int index) { public static <T> T get(T[] array, int index) {
@ -14,9 +15,9 @@ public class ArrayUtils {
return t == null ? fallback : t; return t == null ? fallback : t;
} }
public static <T> T get(T[] array, int index, Function<T[], T> fallbackFunction) { public static <T> T get(T[] array, int index, Supplier<T> fallbackFunction) {
T t = get(array, index); T t = get(array, index);
return t == null ? fallbackFunction.apply(array) : t; return t == null ? fallbackFunction.get() : t;
} }
public static <T, R> R[] map(T[] array, IntFunction<R[]> arrayConstructor, Function<T, R> function) { public static <T, R> R[] map(T[] array, IntFunction<R[]> arrayConstructor, Function<T, R> function) {

View file

@ -4,6 +4,7 @@ import java.util.Collection;
import java.util.List; import java.util.List;
import java.util.function.Function; import java.util.function.Function;
import java.util.function.IntFunction; import java.util.function.IntFunction;
import java.util.function.Supplier;
public class CollectionUtils { public class CollectionUtils {
public static <T> T get(List<T> list, int index) { public static <T> T get(List<T> list, int index) {
@ -15,9 +16,9 @@ public class CollectionUtils {
return t == null ? fallback : t; return t == null ? fallback : t;
} }
public static <T> T get(List<T> list, int index, Function<List<T>, T> fallbackFunction) { public static <T> T get(List<T> list, int index, Supplier<T> fallbackFunction) {
T t = get(list, index); T t = get(list, index);
return t == null ? fallbackFunction.apply(list) : t; return t == null ? fallbackFunction.get() : t;
} }
public static <C extends Collection<R>, T, R> C map(Collection<T> collection, IntFunction<C> collectionConstructor, Function<T, R> function) { public static <C extends Collection<R>, T, R> C map(Collection<T> collection, IntFunction<C> collectionConstructor, Function<T, R> function) {