All Downloads are FREE. Search and download functionalities are using the official Maven repository.

net.dongliu.commons.collection.Raws Maven / Gradle / Ivy

There is a newer version: 6.7.0
Show newest version
package net.dongliu.commons.collection;

import javax.annotation.Nullable;
import java.lang.reflect.Array;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;

/**
 * Utils to deal raw list/map
 *
 * @author Liu Dong
 */
public class Raws {

    /**
     * Get load from raw list as Type T
     */
    @SuppressWarnings("unchecked")
    public static @Nullable  T extract(List list, Object... keys) {
        return _extract(list, keys);
    }

    /**
     * Get load from raw map
     */
    @SuppressWarnings("unchecked")
    public static @Nullable  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")
    public static @Nullable  T _extract(Object container, Object... keys) {
        for (Object key : keys) {
            Objects.requireNonNull(key);
        }
        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