MapUtils 예제이다. (대부분 익숙해지면 되는데, 특별히 한 메소드는 잘 살펴봐야 한다. )


import java.util.Map;


import junit.framework.Assert;


import org.apache.commons.collections.MapUtils;

import org.junit.Test;


import com.google.common.collect.Maps;


public class MapUtilsTest {


@Test

public void test() {

Map<String, Object> map = Maps.newHashMap();

map.put("1", "1");

map.put("3", "3");

map.put("2", "2");

map.put("bool", true);

map.put("int", 1);

System.out.println("empty ? " + MapUtils.isEmpty(map));

System.out.println("not empty ? " + MapUtils.isNotEmpty(map));

MapUtils.debugPrint(System.out, "label", map);

Map<String, Object> fixedSizedMap = MapUtils.fixedSizeMap(map);

try {

fixedSizedMap.put("error", "error"); // exception ocurred

// java.lang.IllegalArgumentException: Cannot put new key/value pair - Map is fixed size

} catch (Exception e) {

System.err.println("exception :" + e);

}

// ------- bool 

System.out.println("boolean--");

// map에 데이터가 있는 경우 

System.out.println(MapUtils.getBoolean(map, "bool")); // true

System.out.println(MapUtils.getBooleanValue(map, "bool")); //true


  // map에 데이터가 없는 경우

System.out.println(MapUtils.getBoolean(map, "nodata"));  // null (주의)

System.out.println(MapUtils.getBooleanValue(map, "nodata")); // false

// map에 데이터가 없으면 default 값 주기

System.out.println(MapUtils.getBoolean(map, "nodata", false));  // false

//---------int

System.out.println("int--");

// map에 데이터가 있는 경우 

System.out.println(MapUtils.getInteger(map, "int")); // true

System.out.println(MapUtils.getIntValue(map, "int")); //true


  // map에 데이터가 없는 경우

System.out.println(MapUtils.getInteger(map, "nodata"));  // null (주의)

System.out.println(MapUtils.getIntValue(map, "nodata")); // false

// map에 데이터가 없으면 default 값 주기

System.out.println(MapUtils.getInteger(map, "nodata", 0));  // false

// -------- sub map

System.out.println("map--");

// key, value를 모두 변경 

Map<String, Object> invertedMap = MapUtils.invertMap(map);

MapUtils.debugPrint(System.out, "inverted map", invertedMap); 

System.out.println();

 // org.apache.commons.collections.map.MultiValueMap 으로 변경 

Map<String, Object> multiValuedMap = MapUtils.multiValueMap(map); 

MapUtils.debugPrint(System.out, "multivalued map", multiValuedMap);

System.out.println();

Map<String, Object> testMap = MapUtils.getMap(map, "2");

System.out.println(testMap); // null

Map<String, Object> subMap = Maps.newHashMap();

subMap.put("subkey1", "1");

subMap.put("subkey2", "2");

map.put("subMap", subMap);

MapUtils.debugPrint(System.out, "sub map", subMap); 

System.out.println();

Map<String, Object> orderedMap = MapUtils.orderedMap(map);

MapUtils.debugPrint(System.out, "ordered map", orderedMap); 

System.out.println();

Map<String, Object> putalledMap = MapUtils.putAll(subMap, new String[][] {{"key1", "5"}, {"key2", "6"}});

MapUtils.debugPrint(System.out, "putalled map", putalledMap); 

MapUtils.verbosePrint(System.out, "putalled map", putalledMap); 

// -- 

Map<String, Object> syncMap = MapUtils.synchronizedMap(map);

org.junit.Assert.assertSame("java.util.Collections$SynchronizedMap", syncMap.getClass().getName());

Object value = null;

MapUtils.safeAddToMap(map, "XXXXXXXXXXX", value); // null이면 ""으로 put이 되게 한다.

org.junit.Assert.assertSame(MapUtils.getObject(map, "XXXXXXXXXXX"), "");

Map<String, Object> unmodifableMap = MapUtils.unmodifiableMap(map);

org.junit.Assert.assertSame("org.apache.commons.collections.map.UnmodifiableMap", unmodifableMap.getClass().getName());

}

}






결과 

empty ? false

not empty ? true

label = 

{

    3 = 3 java.lang.String

    2 = 2 java.lang.String

    1 = 1 java.lang.String

    int = 1 java.lang.Integer

    bool = true java.lang.Boolean

} java.util.HashMap

boolean--

exception :java.lang.IllegalArgumentException: Cannot put new key/value pair - Map is fixed size

true

true

null

false

false

int--

1

1

null

0

0

map--

inverted map = 

{

    3 = 3 java.lang.String

    1 = int java.lang.String

    2 = 2 java.lang.String

    true = bool java.lang.String

    1 = 1 java.lang.String

} java.util.HashMap


multivalued map = 

{

    3 = 3 java.lang.String

    2 = 2 java.lang.String

    1 = 1 java.lang.String

    int = 1 java.lang.Integer

    bool = true java.lang.Boolean

} org.apache.commons.collections.map.MultiValueMap


null

sub map = 

{

    subkey2 = 2 java.lang.String

    subkey1 = 1 java.lang.String

} java.util.HashMap


ordered map = 

{

    3 = 3 java.lang.String

    2 = 2 java.lang.String

    1 = 1 java.lang.String

    int = 1 java.lang.Integer

    bool = true java.lang.Boolean

    subMap = 

    {

        subkey2 = 2 java.lang.String

        subkey1 = 1 java.lang.String

    } java.util.HashMap

} org.apache.commons.collections.map.ListOrderedMap


putalled map = 

{

    subkey2 = 2 java.lang.String

    subkey1 = 1 java.lang.String

    key2 = 6 java.lang.String

    key1 = 5 java.lang.String

} java.util.HashMap

putalled map = 

{

    subkey2 = 2

    subkey1 = 1

    key2 = 6

    key1 = 5

}




MapUtils.getXXX()와 getXXXValue()가 존재하는데, 엄청난 차이가 있다. 

즉, Class로 처리하느냐 Primitive 로 처리하느냐이다. 관련해서 처음에서는 엄청 혼동된다.  


System.out.println(MapUtils.getBoolean(map, "nodata"));  // null (주의)

System.out.println(MapUtils.getBooleanValue(map, "nodata")); // false



예제처럼 getBoolean()할때 Boolean 객체를 리턴하는데, 이 때 null이 될 수 있다. 따라서 boolean primitive 타입을 원한다면 getBooleanValue()를 사용해야 한다. 이를 잘 활용해서 NPE가 발생하지 않도록 해야 한다. 




* 참고


Collection 3.x의 MapUtils.getMap()과 같이 Map을 리턴하는 메소드는 Generic을 지원하지 않는다. 그러나 4.x 부터는 Generic을 지원한다. (3,4의 큰 차이가 Generic) 


Collection 3.x의 MapUtils.getMap()

    public static Map getMap(final Map map, final Object key) {

        if (map != null) {

            Object answer = map.get(key);

            if (answer != null && answer instanceof Map) {

                return (Map) answer;

            }

        }

        return null;

    }


Collections 4.x의 MapUtils.getMap()

https://apache.googlesource.com/commons-collections/+/43e4df85bda71ca1500112912a83d3ed19868c4c/src/main/java/org/apache/commons/collections4/MapUtils.java

    public static <K> Map<?, ?> getMap(final Map<? super K, ?> map, final K key) {

        if (map != null) {

            final Object answer = map.get(key);

            if (answer != null && answer instanceof Map) {

                return (Map<?, ?>) answer;

            }

        }

        return null;

    }







Posted by '김용환'
,