Apache工具类


Apache工具类

Apache集合全家桶,里边功能超级多,想用啥直接去api里边找就行。

http://commons.apache.org/proper/commons-lang/javadocs/api-release/index.html

平时最常用集合工具类有5个:
CollectionUtils,ListUtils,SetUtils,MapUtils,ArrayUtils

Apache的工具类比java自带的工具好用。

<dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-collections4</artifactId>
      <version>4.2</version>
</dependency>

1、MapUtils

MapUtils对基本数据类型及其包装类分别提供以下方法:

//从不定类型的map中获取值,并将值转化为int,值为空时返回0
public static int getIntValue(final Map map, final Object key) {
    Integer integerObject = getInteger(map, key);
    if (integerObject == null) {
        return 0;
    }
    return integerObject.intValue();
}

//从map中获取值,并将值的类型转化为int,值为空时采用默认值defaultValue
public static int getIntValue(final Map map, final Object key, int defaultValue) {
    Integer integerObject = getInteger(map, key);
    if (integerObject == null) {
        return defaultValue;
    }
    return integerObject.intValue();
}

//从map中获取值,并将值的类型转化为Integer,值为空时返回null
public static Integer getInteger(final Map map, final Object key) {
    Number answer = getNumber(map, key);
    if (answer == null) {
        return null;
    } else if (answer instanceof Integer) {
        return (Integer) answer;
    }
    return new Integer(answer.intValue());
}

//从map中获取值,并将值的类型转化为Integer,值为空时采用默认值defaultValue
public static Integer getInteger( Map map, Object key, Integer defaultValue ) {
    Integer answer = getInteger( map, key );
    if ( answer == null ) {
        answer = defaultValue;
    }
    return answer;
}

其它常用方法

//用于添加数据
//防止向map中加入null,如果值为null,则用""替代
public static void safeAddToMap(Map map, Object key, Object value) throws NullPointerException {
    if (value == null) {
        map.put(key, "");
    } else {
        map.put(key, value);
    }
}

//判空,判非空
boolean empty = MapUtils.isEmpty(map);
boolean notEmpty = MapUtils.isNotEmpty(map);

//将二维数组放入map
//索引为0的值为key,索引为2的值为value
//names为key,zhangfsan为value
String[][] user = {{"names","zhangfsan"},{"sexs","1f"}};
Map map1 = MapUtils.putAll(map, user);

  目录