赞
踩
@FunctionalInterface
public interface MyFunction {
public String getValue(String str);
}
@FunctionalInterface
public interface MyFunc<T> {
public R getValue(T t);
}
@FunctionalInterface
public interface MyFunc<T> {
public T getValue(T t);
}
public String toUpperString(MyFunc<String> mf, String str) {
mf.getValue(str)
}
//Lambda 表达式作为参数传递
String str1 = toUpperString(str -> str.toUpperCase(),"abcd");
sout(str1 )
//Consumer: 消费型接口
@Test
public void test1(){
happy(35,d -> System.out.println("花费了"+d));
}
public void happy(double money, Consumer<Double> con){
con.accept(money);
}
@Test public void test2(){ List<Integer> numberList = getNumberList(10, () -> (int) (Math.random() * 100)); for(Integer num : numberList){ System.out.println(num); } } //需求:产生一些整数,并放在集合中 public List<Integer> getNumberList(int num, Supplier<Integer> sup){ List<Integer> list = new ArrayList<>(); for(int i = 0; i < num ; i++){ list.add(sup.get()); } return list; }
@Test
public void test3(){
String result = Strandler("\t\thello world,i like china!", str -> str.trim());
System.out.println(result);
}
//需求:用于处理字符串
public String Strandler(String str, Function<String,String> fun){
return fun.apply(str);
}
@Test public void test4(){ List<String> employees = Arrays.asList("hello","houchen","shuchenxi"); List<String> list = filterStr(employees, str -> str.length() >3); for(String s : list){ System.out.println(s); } } //需求:将满足条件的字符串放入集合中 public List<String> filterStr(List<String> list, Predicate<String> pre){ List<String> stringList = new ArrayList<>(); for(String str : list){ if(pre.test(str)){ stringList.add(str); } } return stringList; }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。