依赖
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-collections4</artifactId> <version>4.4</version></dependency>
示例
package com.demo.map;import org.apache.commons.collections4.MapUtils;import java.util.HashMap;import java.util.Map;public class MapUtilDemo { public static void main(String[] args) { Map<String, Object> map = new HashMap<>(); map.put("age", 12); // Integer age = (Integer) map.getOrDefault("age", 20); Integer age = MapUtils.getInteger(map, "age", 20); System.out.println("age: " + age); // age: 20 }}
如果是字符串类型
Map<String, Object> map = new HashMap<>();map.put("age", "12");// Integer age = (Integer) map.getOrDefault("age", 20);// java.lang.String cannot be cast to java.lang.IntegerInteger age = MapUtils.getInteger(map, "age", 20);System.out.println("age: " + age);// age: 12