【发布时间】:2019-08-04 18:57:56
【问题描述】:
我有一张不可修改的地图 (Map<String, Object>)。这包含一个键值对,其中值应该是一个列表,但对于特定键,值是一个空列表。
如何从地图中删除该空列表并返回?
我已经使用谓词来完成它,该谓词检查值是否是集合的实例,然后检查 Collections.isNotEmpty(..) 是否。
我想知道有没有比这更好的方法? (在 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;
}
}
预期输出:
{student_avg_height=172, student_batch_size=200}
【问题讨论】:
-
如果
instanceof检查失败,您可以取消第二个Predicate并返回false -
能否详细说明。如果它是一个空列表,
instanceof应该返回 true。 -
putAll的使用只是奇怪。collect直接toMap- 你所做的只是增加不必要的认知负荷并创建不必要的对象(中间Map)。 -
是的 -
return inputMap.entrySet()...collect(toMap(...))。您保存了一些冗余代码和Map创建。