測試下java函數語言程式設計的幾個介面
阿新 • • 發佈:2019-09-01
//看著很簡潔,就是有點難理解
public class Iterator_test {
public static void main(String[] args) { List<String> list=new ArrayList<>(); list.add("343"); list.add("343434"); //使用Consumer介面 //函數語言程式設計,消費者 list.forEach((String s)-> {System.out.println(s);}); list.forEach(s->System.out.println(s)); list.forEach(System.out::println); //使用Function介面 String s=Function_test("hello word",(s1)->s1+" wind"); String s2=Function_test("hello word",(s1)->{String a=s1+" hi";return a;}); System.out.println(s); System.out.println(s2); //測試supplier介面 List<Integer> mao=Supplier_test(5,()->(int)(Math.random()*10)); mao.forEach(System.out::println); //測試下斷言介面predicate List<String> list1= Arrays.asList("hello","wored","english","china"); List<String> list2=predicte(list1,(ss)->ss.contains("o")); list2.forEach(System.out::println); } public static String Function_test(String str, Function<String,String> f){ return f.apply(str); }
public static List<Integer> Supplier_test(int n, Supplier<Integer> s){
List<Integer> list =new ArrayList<>();
for(int i=0;i<n;i++)
list.add(s.get());
return list;
}
public static List<String> predicte(List<String> list, Predicate<String> p){
List<String> re=new ArrayList<>();
for (String s:list)
if(p.test(s))
re.add(s);
return re;