美文网首页
MapUtils 工具类

MapUtils 工具类

作者: 凯睿看世界 | 来源:发表于2020-08-05 23:02 被阅读0次

    MapUtils是 Apache Commons 工具包中常用的工具类,使用是需要依赖对应的lab,对应的maven引用如下:

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

    MapUtils 常用操作java.util.Map 和 java.util.SortedMap。

    常用方法有:
    isNotEmpty ( ) 是否不为空
    isEmpty ( ) 是否为空
    putAll ( ) 添加所有元素
    getString ( ) 获取String类型的值
    getObject ( ) 获取Object类型的值
    getInteger ( )获取Integer类型的值
    get*** ( ) 类似上面的
    EMPTY_MAP 获取一个不可修改的空类型Map
    unmodifiableMap 获取一个不可以修改的Map(不能新增或删除)
    unmodifiableSortedMap 获取一个不可以修改的有序的Map(不能新增或删除)
    fixedSizeMap 获取一个固定长度的map
    multiValueMap 获取一个多值的map(即一个key可以对应多个value值)
    invertMap 返回一个key与value对调的map
    predicatedMap() 返回一个满足predicate条件的map
    lazyMap 返回一个lazy的map(值在需要的时候可以创建)

    String name = MapUtils.getString(map, "name");
    
    int money = MapUtils.getInteger(map,"money");//包装类型自动拆箱
    
    boolean empty = MapUtils.isEmpty(map);
    
    boolean notEmpty = MapUtils.isNotEmpty(map);
    
    //把二维数组转换成map
    String[][] user = {{"names","zhangfsan"},{"sexs","1f"}};
    Map map1 = MapUtils.putAll(map, user);
    
    public class MapUtilsTest {
        private String[][] color2DArray = new String[][] {
            {"RED", "#FF0000"},
            {"GREEN", "#00FF00"},
            {"BLUE", "#0000FF"}
        };
        private String[] color1DArray = new String[] {
            "RED", "#FF0000",
            "GREEN", "#00FF00",
            "BLUE", "#0000FF"
        };
        private Map<String, String> colorMap;
     
        //...
    }
    
    @Test
    public void whenCreateMapFrom2DArray_theMapIsCreated() {
        this.colorMap = MapUtils.putAll(
          new HashMap<>(), this.color2DArray);
     
        assertThat(
          this.colorMap, 
          is(aMapWithSize(this.color2DArray.length)));
        
        assertThat(this.colorMap, hasEntry("RED", "#FF0000"));
        assertThat(this.colorMap, hasEntry("GREEN", "#00FF00"));
        assertThat(this.colorMap, hasEntry("BLUE", "#0000FF"));
    }
    
    @Test
    public void whenCreateMapFrom1DArray_theMapIsCreated() {
        this.colorMap = MapUtils.putAll(
          new HashMap<>(), this.color1DArray);
        
        assertThat(
          this.colorMap, 
          is(aMapWithSize(this.color1DArray.length / 2)));
     
        assertThat(this.colorMap, hasEntry("RED", "#FF0000"));
        assertThat(this.colorMap, hasEntry("GREEN", "#00FF00"));
        assertThat(this.colorMap, hasEntry("BLUE", "#0000FF"));
    }
    
    @Test
    public void whenVerbosePrintMap_thenMustPrintFormattedMap() {
        MapUtils.verbosePrint(System.out, "Optional Label", this.colorMap);
    }
    
    /**
    Optional Label = 
    {
        RED = #FF0000
        BLUE = #0000FF
        GREEN = #00FF00
    }
    /*
    
    @Test
    public void whenGetKeyNotPresent_thenMustReturnDefaultValue() {
        String defaultColorStr = "COLOR_NOT_FOUND";
        String color = MapUtils
          .getString(this.colorMap, "BLACK", defaultColorStr);
        
        assertEquals(color, defaultColorStr);
    }
    
    @Test
    public void whenGetOnNullMap_thenMustReturnDefaultValue() {
        String defaultColorStr = "COLOR_NOT_FOUND";
        String color = MapUtils.getString(null, "RED", defaultColorStr);
        
        assertEquals(color, defaultColorStr);
    }
    
    @Test
    public void whenInvertMap_thenMustReturnInvertedMap() {
        Map<String, String> invColorMap = MapUtils.invertMap(this.colorMap);
     
        int size = invColorMap.size();
        Assertions.assertThat(invColorMap)
          .hasSameSizeAs(colorMap)
          .containsKeys(this.colorMap.values().toArray(new String[] {}))
          .containsValues(this.colorMap.keySet().toArray(new String[] {}));
    }
    
    /**
    {
        #00FF00 = GREEN
        #FF0000 = RED
        #0000FF = BLUE
    }
    */
    
    @Test(expected = IllegalArgumentException.class)
    public void whenCreateFixedSizedMapAndAdd_thenMustThrowException() {
        Map<String, String> rgbMap = MapUtils
          .fixedSizeMap(MapUtils.putAll(new HashMap<>(), this.color1DArray));
        
        rgbMap.put("ORANGE", "#FFA500");
    }
    
    @Test(expected = IllegalArgumentException.class)
    public void whenAddDuplicate_thenThrowException() {
        Map<String, String> uniqValuesMap 
          = MapUtils.predicatedMap(this.colorMap, null, 
            PredicateUtils.uniquePredicate());
        
        uniqValuesMap.put("NEW_RED", "#FF0000");
    }
    
    @Test
    public void whenCreateLazyMap_theMapIsCreated() {
        Map<Integer, String> intStrMap = MapUtils.lazyMap(
          new HashMap<>(),
          TransformerUtils.stringValueTransformer());
        
        assertThat(intStrMap, is(anEmptyMap()));
        
        intStrMap.get(1);
        intStrMap.get(2);
        intStrMap.get(3);
        
        assertThat(intStrMap, is(aMapWithSize(3)));
    }
    

    参考:
    https://tool.oschina.net/uploads/apidocs/commons-collections/index.html?org/apache/commons/collections/MapUtils.html
    https://www.baeldung.com/apache-commons-map-utils
    https://www.programcreek.com/java-api-examples/index.php?api=org.apache.commons.collections.MapUtils
    https://www.codota.com/code/java/methods/org.apache.commons.collections.MapUtils/getInteger
    https://www.techiedelight.com/initialize-map-using-apache-commons-collections-java/

    相关文章

      网友评论

          本文标题:MapUtils 工具类

          本文链接:https://www.haomeiwen.com/subject/ukdarktx.html