에 "불가능한"지도에서 null 또는 빈 목록을 제거하는 방법

RoyalTiger :

내가 변경 불가능한 맵을 ( Map<String, Object>). 이 값이 목록해야 키 - 값 쌍을 포함하지만, 특정 키에 대한 값은 빈 목록입니다.

어떻게지도 및 반환에서 그 빈 목록을 제거 할 수 있습니까?

I는 다음 체크 값 컬렉션 인스턴스인지 확인 술어를 사용했을 Collections.isNotEmpty (..) 경우.

나는 어떤 더 나은 방법이보다이 알고 싶어? (자바 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;
    }

}

예상 출력 :

{student_avg_height=172, student_batch_size=200}
앤드류 Tobilko :

Collection#removeIf 고려해야 할 좋은 옵션이 될 수 있습니다.

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;
}

스트림 기반의 접근 방식은 당신에게 더 매력적 경우

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));
}

최신 정보

당신이 널 (null)이 자신의 유형에 관계없이 객체를 필터링 할 경우, 여기에 위에서 언급 한 방법에 약간의 변경 사항은

1) removeIf

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

2) 스트림 기반

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

추천

출처http://43.154.161.224:23101/article/api/json?id=333962&siteId=1