说几个,我最近用到的Google Guava Collections
public static void main(String[] args){
//简化Map new对象的步骤
Map<String,String> map = Maps.newHashMap();
Map<String,String> map1 = ImmutableMap.of(
"1", "String1",
"2", "String2"
);
Map<String,String> map2 = ImmutableMap.<String,String>of(
"1", "String1",
"2", "String2"
);
//Google Guava Collections
//使用Collections.unmodifiable***()实现集合不可变
Set<String> set = Sets.newHashSet();
set.add("String1");
set.add("String2");
set.add("String2");
Set<String> unmodifiableSet = Collections.unmodifiableSet(set);
// 如果再接着下面一条语句,便会报UnsupportedOperationException异常
//unmodifiableSet.add("String3");
System.out.println("unmodifiableSet : " + unmodifiableSet);
//1、Immutable Collections:真正的不可修改的集合
//a、ImmutableSet
ImmutableSet<String> immutableSet = ImmutableSet.of("String1","String2","String2");
System.out.println("immutableSet : " + immutableSet);
//此外, ImmutableSet还提供了builder方法构造
ImmutableSet.Builder<String> builder = ImmutableSet.builder();
ImmutableSet<String> immutableSet1 = builder.add("String1").add("String2").add("String2").build();
System.out.println("immutableSet,builder : " + immutableSet1 );
//b、ImmutableMap
ImmutableMap<Integer,String> immutableMap = ImmutableMap.of(
1,"String1",
2,"String2"
);
System.out.println("immutableMap : " + immutableMap);
ImmutableMap.Builder<Integer,String> builderMap = ImmutableMap.builder();
ImmutableMap<Integer,String> immutableMap1 = builderMap.put(1,"String1").put(2,"String2").build();
System.out.println("immutableMap,builder : " + immutableMap1);
//2、Multiset:重复的元素放入一个集合,并没有实现Set接口
//a、统计一个字符串中出现“a“重复出现的次数
List<String> wordList = ImmutableList.of(
"a","b","c","a"
);
HashMultiset<String> multiset = HashMultiset.create();
multiset.addAll(wordList);
System.out.println("a : " +multiset + " count : " + multiset.count("a"));
//3、Multimap:一个key可以对应多个value,如一个班级对应多名学生
Multimap<String,String> multimap = HashMultimap.create();
multimap.put("one","zhangsan");
multimap.put("one","wangwu");
multimap.put("two","甲");
multimap.put("two","乙");
multimap.put("two","丙");
multimap.put("three","甲");
multimap.put("three","乙");
multimap.put("three","丙");
System.out.println("multimap : "+multimap);
//4、BiMap:在保证key唯一的同时,也保证了value的唯一
BiMap<String,String> biMap = HashBiMap.create();
biMap.put("a","1");
biMap.put("b","2");
System.out.println("根据key得到value: " + biMap.get("a"));
System.out.println("根据value得到key : " + biMap.inverse().get("1"));
}
最后的结果:
ps:jdk要在5以上o