¿Cómo eliminar nulo o lista vacía de un mapa "inmodificable"

RoyalTiger :

Tengo un mapa inmodificable ( Map<String, Object>). Este contiene un par clave-valor, donde el valor debe ser una lista, pero para una tecla específica el valor es una lista vacía.

¿Cómo puedo eliminar esa lista vacía del mapa y de retorno?

Lo he hecho usando predicado que comprueba si el valor es una instancia de recogida y a continuación, comprobar si Collections.isNotEmpty (..).

Quiero saber ¿hay algún método mejor que esto? (En Java 8)

public class StudentTest {

    Predicate<Object> isCollectionNotEmpty = input -> {
        if (input instanceof Collection) {
            return CommonCollectionUtils.isNotEmpty((Collection<?>)input);
        }
        return true;
    };
    Predicate<Object> isObjectNotNull = input -> Objects.nonNull(input);

    public static void main(String[] args) {

        StudentTest s = new StudentTest();
        final Map<String, Object> map1 = new HashMap<>();
        map1.put("student_batch_size", 200);
        map1.put("student_avg_height", 172);
        map1.put("Student_names", Collections.emptyList());

        final Map<String, Object> finalMap = s.getFinalMap(Collections.unmodifiableMap(map1));

        System.out.println(finalMap);
    }

    private Map<String, Object> getFinalMap(final Map<String, Object> inputMap) {
        final Map<String, Object> resultMap = new HashMap<>();
        //inputMap.values().remove(Collections.emptyList());
        resultMap.putAll(inputMap.entrySet().stream()
            .filter(entry -> isObjectNotNull.and(isCollectionNotEmpty).test(entry.getValue()))
        .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue())));
        return resultMap;
    }

}

Rendimiento esperado:

{student_avg_height=172, student_batch_size=200}
Andrew Tobilko:

Collection#removeIf podría ser una buena opción a considerar.

private Map<String, Object> getFinalMap(final Map<String, Object> inputMap) {
    final Map<String, Object> resultMap = new HashMap<>(inputMap);
    resultMap.entrySet().removeIf(e -> e.getValue() instanceof Collection && ((Collection) e.getValue()).isEmpty());

    return resultMap;
}

Si un enfoque basado en el flujo es más atractiva para usted

private Map<String, Object> getFinalMap(final Map<String, Object> inputMap) {
    return inputMap.entrySet()
        .stream()
        .filter(e -> !(e.getValue() instanceof Collection && ((Collection) e.getValue()).isEmpty()))
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
}

ACTUALIZAR

Si desea filtrar los objetos nulos independientemente de su tipo, aquí hay ligeros cambios en los métodos mencionados anteriormente

1) removeIf

resultMap.entrySet()
    .removeIf(e -> Objects.isNull(e.getValue()) || 
                   (e.getValue() instanceof Collection && ((Collection) e.getValue()).isEmpty());

2) flujo de base

.filter(e -> Objects.nonNull(e.getValue()))
.filter(e -> !(e.getValue() instanceof Collection && ((Collection) e.getValue()).isEmpty()))

Supongo que te gusta

Origin http://43.154.161.224:23101/article/api/json?id=333968&siteId=1
Recomendado
Clasificación