一,对集合设置只读
List<String> list
= new ArrayList<String>();
list.add("a");
list.add("b");
list.add("c");
//对比查看初始化list grava 对只读设置安全可靠,并且相对简单
List<String> immutableList = ImmutableList.of("A","B","C");
immutableList.add("c");
System.out.println(immutableList);//java.lang.UnsupportedOperationException
}
二,过滤器,更好的与集合类解耦
1,查看集合中的回文单词,字符
注意:
如果一个类只使用一次,并且这个类 的对象也只是用一次,那么我们就是用匿名内部类
工具:Collections2.filter 过滤器
函数式编程
//List的静态初始化
List<String> list
= Lists.newArrayList("ab","bcb","cd","son","mom");
//找出回文 mirror words
//匿名内部类的对象:匿名内部类,同时创建类对象
Collection<String> parlidromeList = Collections2.filter(list, new Predicate<String>(){
@Override
public boolean apply(String input) {
//业务逻辑
return new StringBuilder(input).reverse().toString().equals(input);
}
});
for(String tem:parlidromeList){
System.out.println(tem);
}
}
2,确保容器中字符串的长度不超过5,超过进行截取,并且全部大写
//组合式函数编程
//确保容器中字符串的长度不超过5,超过进行截取,并且全部大写
List<String> lists = Lists.newArrayList("good","happy","wonderful");
//确保容器中字符串的长度不超过5,超过进行截取
Function<String,String> f1
= new Function<String,String>(){
@Override
public String apply(String input) {
return input.length()>5?input.substring(0,5):input;
}
};
//转成大写
Function<String,String> f2
= new Function<String,String>(){
@Override
public String apply(String input) {
return input.toUpperCase();
}
};
//现在需要将f1和f2组合在一起 String combinedStr = f2(f1(String))
Function<String,String> f
= Functions.compose(f1, f2);
Collection<String> resultCol
= Collections2.transform(lists, f);
for(String tem:resultCol){
System.out.println(tem);
}
}
3,添加约束条件(非空,长度验证)
Set<String> st = Sets.newHashSet();
//创建约束
Constraint<String> constraint
= new Constraint<String>(){
@Override
public String checkElement(String element) {
//非空验证
Preconditions.checkNotNull(element);
//长度验证
Preconditions.checkArgument(element.length()>=5 && element.length()<=20);
return element;
}
};
Set<String> cs
= Constraints.constrainedSet(st, constraint);
//cs.add("good");//java.lang.IllegalArgumentException
//cs.add("");//java.lang.IllegalArgumentException
//cs.add(null);//java.lang.NullPointerException
cs.add("wonderful");//添加成功
System.out.println(cs);
}
4,集合的操作:交集,差集,并集
Set<Integer> set1 = Sets.newHashSet(1,2,3,4,6);
Set<Integer> set2 = Sets.newHashSet(2,4,6,7);
//交集
System.out.println("交集为:");
SetView<Integer> intersections
= Sets.intersection(set1, set2);
System.out.println(intersections);
//差集
System.out.println("差集为:");
SetView<Integer> diff
= Sets.difference(set1, set2);
System.out.println(diff);
//并集
System.out.println("并集为:");
SetView<Integer> union
= Sets.union(set1, set2);
System.out.println(union);
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。