Java容器-引入Guava类库
目录
1、只读设置
2、函数式编程+组合式编程
3、约束条件
4、集合操作(并集、差集、交集)
代码实现
1、只读设置
public static void main(String [] args){
//只读设置
List ls=new ArrayList();
ls.add("a");
ls.add("b");
ls.add("c");
//不使用guava的类库
List readList= Collections.unmodifiableList(ls);
//readList.add("d"); 报错
//使用guava的类库
List imutableList= ImmutableList.of("a","b","c");
//imutableList.add("a"); 运行报错
}
2、函数式编程
(1)函数一:找出集合众的回文字符串,回文又称 mirror word ,backword,是指字符串从前面或者后面读都是一样的,比如moom
//结果:moom 因为moon逆序以后还是moom
public static void main(String[] args) {
List list = Lists.newArrayList("dog", "cat", "pig", "moom");
Collection pList=Collections2.filter(list, new Predicate() {
public boolean apply(String s) {
return new StringBuilder(s).reverse().toString().equals(s);
}
});
// 匿名内部类,同时创建对象,Collections2.filter类似过滤器
for(Object o:pList){
System.out.println(o);
}
}
(2)函数二:日期转换
//结果:1970-01-01 1970-01-24 1970-01-02
public static void main(String [] args){
Set timeSet= Sets.newHashSet();
timeSet.add(1000L);
timeSet.add(2000L*1000000);
timeSet.add(3000L*20000);
Collection transList= Collections2.transform(timeSet, new Function() {
public String apply(Long input) {
return new SimpleDateFormat("yyyy-MM-dd").format(input);
}
});
for(String s:transList){
System.out.println(s);
}
}
(3)函数三:组合式编程
public static void main(String [] args){
List list = Lists.newArrayList("happy", "sad", "wahaha");
//方法一
Functionf1=new Function() {
public String apply(String s) {
return s.length()>5&&s.length()<20?s:"error";
}
};
//方法二:字母全部大写
Function f2 = new Function() {
public String apply(String input) {
return input.toUpperCase();
}
};
//组合方法
Function f = Functions.compose(f1, f2);
Collection resultCol=Collections2.transform(list,f);
for(Object s:resultCol){
System.out.println(s);
}
}
3、约束条件
public static void main(String[] args) {
Set sets = Sets.newHashSet();
// 创建约束
Constraint constraint = new Constraint() {
@Override
public String checkElement(String element) {
// 非空验证
Preconditions.checkNotNull(element);
// 长度限制 5-20,否则报错
Preconditions.checkArgument(
element.length() >= 5 && element.length() <= 20,
element);
return element;
}
};
Set cs = Constraints.constrainedSet(sets, constraint);
// cs.add(null); 报错java.lang.NullPointerException
//cs.add("qaz"); 报错java.lang.IllegalArgumentException: qaz
}
4、交集、并集、差集
public static void main(String [] args){
Set sets=Sets.newHashSet(1,2,3,4,5,6);
Set set2=Sets.newHashSet(3,4,5,6,7,8,9);
Sets.SetView intersection =Sets.intersection(sets, set2);
for(Integer in:intersection){
System.out.print(in+" ");
}
System.out.println("");
//差集
Sets.SetView intersection2=Sets.difference(sets,set2);
for(Integer in:intersection2){
System.out.print(in+" ");
}
System.out.println("");
//并集
Sets.SetView intersection3=Sets.union(sets,set2);
for(Integer in:intersection3){
System.out.print(in+" ");
}
}
posted @
2017-03-18 19:43 邱勇Aries 阅读(
...) 评论(
...) 编辑 收藏