美文网首页
guava之ImmutableMap

guava之ImmutableMap

作者: 王金松 | 来源:发表于2019-05-11 21:32 被阅读0次

应用场景

可以让java代码也能够创建一个对象常量映射,来保存一些常量映射的键值对。

maven

<!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
<dependency>    
<groupId>com.google.guava</groupId>    
<artifactId>guava</artifactId>    
<version>21.0</version>
</dependency>

使用方式

interface ConstantMap {
Map<Integer, String> ANIMAL_MAP =      
new ImmutableMap.Builder<Integer, String>()          
.put(1, "cat")          
.put(2, "dog")          
.put(3, "cattle")          
.put(4, "sheep")           
.build();
}

public static void main(String[] args) {
System.out.println(ConstantMap.ANIMAL_MAP.get(3))
}

用于代替以下情况

String animal = ""
if (type == 1) {
animal = "cat"
} else if (type==2) {
animal = "dog"
} ....

copy

Map<String, String> result = Maps.newHashMap();
    return ImmutableMap.copyOf(result);

相关文章

网友评论

      本文标题:guava之ImmutableMap

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