# 集合
# 普通Collection的创建
List<String> list = Lists.newArrayList();
Set<String> set = Sets.newHashSet();
Map<String, String> map = Maps.newHashMap();
# 不变Collection的创建
ImmutableList<String> iList = ImmutableList.of("a", "b", "c");
ImmutableSet<String> iSet = ImmutableSet.of("e1", "e2");
ImmutableMap<String, String> iMap = ImmutableMap.of("k1", "v1", "k2", "v2");
# 创建Map key为String类型,value为List
Multimap<String,Integer> map = ArrayListMultimap.create();
map.put("aa", 1);
map.put("aa", 2);
System.out.println(map.get("aa")); //[1, 2]
# 创建Map 键与值都不能重复
BiMap<String, String> biMap = HashBiMap.create();
biMap.put("1", "1");
biMap.put("1", "1");
System.out.println(biMap);//{1=1}
# 双向Map key 能查询到value value 可以查询到key
Table<String, String, Integer> tables = HashBasedTable.create();
/**
* rowKey
* columnKey
* value
*/
tables.put("rowKey", "columnKey", 2);
Integer integer = tables.get("rowKey", "columnKey");
System.out.println(integer);
/**
* columnKey
*/
Map<String, Integer> column = tables.column("columnKey");
System.out.println(column);
# 将集合转换为特定规则的字符串
ImmutableList<Integer> list = ImmutableList.of(1, 2, 3, 4, 5);
String join = Joiner.on("-").join(list);
System.out.println(join);
# 把map集合转换为特定规则的字符串
Map<String, Integer> map = Maps.newHashMap();
map.put("xiaoming", 12);
map.put("xiaohong",13);
String result = Joiner.on("\n").withKeyValueSeparator("=").join(map);
System.out.println(result);
// result为
// xiaoming=12
// xiaohong=13
# 将String转换为特定的集合
String str = "1-2-3-4-5-6";
List<String> list = Splitter.on("-").splitToList(str);
//list为 [1, 2, 3, 4, 5, 6]
# 去除空串与空格
String str = "1-2-3-4- 5- 6 ";
List<String> list = Splitter.on("-").omitEmptyStrings().trimResults().splitToList(str);
System.out.println(list);//[1, 2, 3, 4, 5, 6]
# 将String转换为map
String str = "xiaoming=11,xiaohong=23";
Map<String,String> map = Splitter.on(",").withKeyValueSeparator("=").split(str);
# 多字符切割
String input = "aa.dd,,ff,,.";
List<String> result = Splitter.onPattern("[.|,]").omitEmptyStrings().splitToList(input);
System.out.println(result);//[aa, dd, ff]
# 过滤
# List
ImmutableList<String> names = ImmutableList.of("begin", "code", "Guava", "Java");
Iterable<String> fitered = Iterables.filter(names, Predicates.or(Predicates.equalTo("Guava"), Predicates.equalTo("Java")));
System.out.println(fitered); //[Guava, Java]
# 自定义过滤
//自定义过滤条件 使用自定义回调方法对Map的每个Value进行操作
ImmutableMap<String, Integer> m = ImmutableMap.of("begin", 12, "code", 15);
// Function<F, T> F表示apply()方法input的类型,T表示apply()方法返回类型
Map<String, Integer> m2 = Maps.transformValues(m, input -> {
if(input > 12){
return input;
}else{
return input + 1;
}
});
System.out.println(m2);
//{begin=13, code=15}
# 断言
int count = -1;
Preconditions.checkArgument(count > 0, "must be positive: %s", count);
//Exception in thread "main" helloworld.md.lang.IllegalArgumentException: must be positive: -1