[java]代码库
需要google的jar包支持
package s0222函数式编程和lambda表达式;
//要用guava的jar包,我重新安装了eclipse 没有关联
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import com.google.common.base.Function;
import com.google.common.base.Functions;
import com.google.common.base.Predicate;
import com.google.common.collect.Collections2;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
public class Main {
public static void main(String [] args)
{
test01(); //容器元素过滤器
test02(); //进行日期转换
test03(); //组合函数
}
public static void test01() //功能:过滤器
{
List<String > list=Lists.newArrayList("moom","bab","coy","kik","dfdfd");
//过滤器,删除不是回文的元素***************************************************
Predicate<String> p=(input)-> new StringBuilder((String) input).reverse().toString().equals(input);
Collection<String> a= Collections2.filter(list, p);
a.forEach(name->System.out.println(name) );//输出每个元素
}
public static void test02() //功能:进行日期转换
{
Collection<Long> timeSet=Sets.newHashSet();
Collections.addAll(timeSet, System.currentTimeMillis(),2000_0000_000L);
//定义函数功能
Function<Long,String> f3=(input)->new SimpleDateFormat("yyyy-MM-dd").format(input);
//对指定容器执行函数
Collection<String> timestrcol= Collections2.transform(timeSet, f3);
//输出每个元素
timestrcol.forEach(name->System.out.println(name) );
}
public static void test03() //功能:确保容器中字符串长度不超过5,并且全部变成大写
{
List<String> list2=Lists.newArrayList("moomwergf","babkjsdhf","coy","kik","dfdfdkd");
//lambda表达式,函数f1,控制容器内元素长度小于等于5
Function<String,String> f1=(input)->input.length()>5?input.substring(0, 5):input;
//lambda表达式,函数f1,将元素转换成大写
Function<String,String> f2=(input)->input.toUpperCase();
//函数式编程,Functions.compose(f1, f2)组合函数f1,和函数f2
Collection<String> list3= Collections2.transform(list2, Functions.compose(f1, f2));
//输出每个元素
list3.forEach(name->System.out.println(name) );
}
}