创建不可变集合
public static final ImmutableSet<String> COLOR = ImmutableSet.<String>builder().add("red").add("yellow").build();
public static final ImmutableSet<String> COLOR2 = ImmutableSet.of("blue","black");
public static final ImmutableSet<String> COLOR3 = ImmutableSet.copyOf(COLOR);
可变集合与不可变集合
计数器Multiset
public static void main(String[] args) {
//计数器
HashMultiset<String> multiset = HashMultiset.create();
for (int i = 0; i < 10; i++) {
multiset.add("a");
multiset.add("b");
}
//批量增加
multiset.add("b",1000);
//批量减少
multiset.remove("b",100);
//获取单个元素个数
System.out.println(multiset.count("a"));
System.out.println(multiset.count("b"));
//获取元素集合
Set<String> set = multiset.elementSet();
set.forEach(System.out::println);
//直接赋值个数
multiset.setCount("b",888);
System.out.println(multiset.count("b"));
//获取总长度
System.out.println(multiset.size());
//
Set<Multiset.Entry<String>> entries = multiset.entrySet();
entries.forEach(System.out::println);
}
10
910
a
b
888
898
a x 10
b x 888
一键映射多值ListMuitimap
System.out.println("==============一键映射多值===============");
ListMultimap<String, String> multimap = ArrayListMultimap.create();
multimap.put("a","a");
multimap.put("a","a");
multimap.put("a","b");
multimap.put("a","c");
multimap.put("a","d");
multimap.put("a","e");
multimap.put("a","f");
multimap.put("b","f");
multimap.put("a",null);
multimap.get("a").forEach(System.out::println);
System.out.println("获取单个键映射值");
multimap.entries().forEach(System.out::println);
System.out.println("获取单个键集合");
multimap.asMap().entrySet().forEach(System.out::println);
System.out.println("获取键映射值的个数");
System.out.println(multimap.size());
System.out.println("获取键");
multimap.keySet().forEach(System.out::println);
System.out.println("获取键的个数");
System.out.println(multimap.keySet().size());
一键映射多值=
a
a
b
c
d
e
f
null
获取单个键映射值
a=a
a=a
a=b
a=c
a=d
a=e
a=f
a=null
b=f
获取单个键集合
a=[a, a, b, c, d, e, f, null]
b=[f]
获取键映射值的个数
9
获取键
a
b
获取键及对应值的个数
2
键值相互映射HashBiMap
由于键值相互映射,因此值也是唯一的,当多个键指向同一个值时,会抛出IllegalArgumentException(参数不合理异常)
当一个键映射多个值时,会发生覆盖。
System.out.println("=============键值相互映射================");
HashBiMap<String,Integer> map = HashBiMap.create();
map.put("a",1);
map.put("b",2);
map.put("b",3);
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey()+":"+entry.getValue());
}
System.out.println("反转map");
BiMap<Integer, String> biMap = map.inverse();
for (Map.Entry<Integer, String> entry : biMap.entrySet()) {
System.out.println(entry.getKey()+":"+entry.getValue());
}
=键值相互映射====
a:1
b:3
反转map
1:a
3:b