天天看點

Java:org.apache.commons.collections4.MapUtils擷取Map資料

依賴

<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.Integer

Integer age = MapUtils.getInteger(map, "age", 20);
System.out.println("age: " + age);
// age: 12