函数式编程
-
过滤
Collections.filter(原内容,过滤规则);返回一个新的list
/**
* 过滤,找出回文
*/
public static void test02() {
List<String> list = Lists.newArrayList("big", "mom", "hoh", "dad", "refer", "Viking");
Collection<String> list2 = Collections2.filter(list, new Predicate<String>() {
// 匿名内部类,只使用一次,因为没有对象名
public boolean apply(String input) {
// 这里不满足要求就会被过滤出去
return new StringBuilder(input).reverse().toString().equals(input);
}
});
for (String temp : list2) {
System.out.println(temp);
}
}
-
转换
Collections2.transform();
public static void main(String[] args) {
//类型转换,function的意思是函数
List<Long> longtime=new ArrayList<>();
longtime.add(100000000L);
longtime.add(999999999999999L);
longtime.add(200000000L);
Collection<String> timeStrCol=Collections2.transform(longtime, new Function<Long, String>() {
public String apply(Long input) {
return new SimpleDateFormat("yyyy-MM-dd").format(input);
}
});
for(String temp:timeStrCol){
System.out.println(temp);
}
}
函数嵌套使用
public static void main(String[] args) {
//组合式函数编程
//确保容器内字符串的长度不超过5,超过得部分截断,然后全转换成大写。
List<String> list=Lists.newArrayList("hello","happiness","Viking","iloveu");
Function<String, String> f1=new Function<String, String>() {
//f1判断是否长度是否大于5,并采取截断操作
public String apply(String input) {
return input.length()>5?input.substring(0, 5):input;
}
};
Function<String, String> f2=new Function<String, String>() {
//f2将字符串转成大写的
public String apply(String input) {
return input.toUpperCase();
}
};
//组合函数
Function<String, String> f=Functions.compose(f1, f2);
Collection<String> col=Collections2.transform(list, f);
for(String temp:col){
System.out.println(temp);
}
}
-
约束
似乎guava里面没有这个Constraint这个类或者借口了
集合的操作
- 交集
sets.intersection(); - 差集
sets.difference(); - 并集
sets.union();
public static void main(String[] args) {
//集合操作
Set<Integer> set1=Sets.newHashSet(1,2,3,4,5,6);
Set<Integer> set2=Sets.newHashSet(4,5,6,7,8,9);
Set<Integer> intersectionSet=Sets.intersection(set1, set2);
System.out.println("交集:");
for(Integer i:intersectionSet)
System.out.print(i+"\t");
Set<Integer> differenceSet=Sets.difference(set1, set2);
System.out.println("\n"+"差集:");
for(Integer i:differenceSet)
System.out.print(i+"\t");
Set<Integer> unionSet=Sets.union(set1, set2);
System.out.println("\n"+"并集:");
for(Integer i:unionSet)
System.out.print(i+"\t");
}