
net.dongliu.commons.collection.RawCollections Maven / Gradle / Ivy
package net.dongliu.commons.collection;
import net.dongliu.commons.Predicates;
import javax.annotation.Nullable;
import java.lang.reflect.Array;
import java.util.List;
import java.util.Map;
/**
* Utils to deal raw list/map
*
* @author Liu Dong
*/
public class RawCollections {
/**
* Get load from raw list as Type T
*/
@SuppressWarnings("unchecked")
@Nullable
public static T extract(List list, Object... keys) {
return _extract(list, keys);
}
/**
* Get load from raw map
*/
@SuppressWarnings("unchecked")
@Nullable
public static T extract(Map map, Object... keys) {
return _extract(map, keys);
}
/**
* Get load from raw List/Map with keys
*
* @return return null if load with keys not found
*/
@SuppressWarnings("unchecked")
@Nullable
public static T _extract(Object container, Object... keys) {
Predicates.checkNotNull(keys);
Object value = container;
for (Object key : keys) {
if (value instanceof List) {
if (!(key instanceof Integer)) {
throw new IllegalArgumentException("value is list, but key type is " + key.getClass().getSimpleName());
}
value = ((List) value).get((Integer) key);
} else if (value instanceof Map) {
value = ((Map) value).get(key);
} else if (value.getClass().isArray()) {
if (!(key instanceof Integer)) {
throw new IllegalArgumentException("value is array, but key type is " + key.getClass().getSimpleName());
}
value = Array.get(value, (Integer) key);
} else {
throw new IllegalArgumentException("Value with type " + value.getClass().getSimpleName()
+ " is not a container");
}
if (value == null) {
return null;
}
}
return (T) value;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy