A Guide to Java HashMap

原文链接: A Guide to Java HashMap → https://www.baeldung.com/java-hashmap


从Map里取值

# 原生方法
Map<String, Integer> map = new HashMap<>();

// map自身的方法 → 取不到返回null
Integer age6 = map.get("name");      // Integer时返回null可以
int age6 = map.get("name");          // int时返回null报错
// map自身的方法 → 取不到使用默认值
Integer age5 = map.getOrDefault("name", 0);
# MapUtils
Map<String, Integer> map = new HashMap<>();

// MapUtils → 取不到返回null
Integer age1 = MapUtils.getInteger(map, "name");     // Integer时返回null可以
int age3 = MapUtils.getInteger(map, "name");         // int时返回null报错

// MapUtils → 取不到使用默认值
Integer age1 = MapUtils.getInteger(map, "name", 0);
int age3 = MapUtils.getInteger(map, "name", 0);

dependency>
   <groupId>commons-collections</groupId>
   <artifactId>commons-collections</artifactId>
   <version>3.2.1</version>
   <scope>compile</scope>
/dependency>

猜你喜欢

转载自blog.csdn.net/weixin_37646636/article/details/132758225