java8特性之函数式接口

编程

java.util.function中 Function, Supplier, Consumer, Predicate和其他函数式接口广泛用在支持lambda表达式的API中。这些接口有一个抽象方法,会被lambda表达式的定义所覆盖。注解都是@FunctionalInterface

Consumer消费

List<Person> lisiList = new ArrayList<>();

Consumer <Person> consumer = x -> {

if (x.name.equals("lisi")){

lisiList.add(x);

}

};

Stream.of(

new Person(21,"zhangsan"),

new Person(22,"lisi"),

new Person(23,"wangwu"),

new Person(24,"wangwu"),

new Person(23,"lisi"),

new Person(26,"lisi"),

new Person(26,"zhangsan")

).forEach(consumer);

System.out.println(JSON.toJSONString(lisiList));

// 结果[{"age":22,"name":"lisi"},{"age":23,"name":"lisi"},{"age":26,"name":"lisi"}]

List<Person> lisiList = new ArrayList<>();

Consumer <Person> consumer = x -> {

if (x.name.equals("lisi")){

lisiList.add(x);

}

};

consumer = consumer.andThen(

x -> lisiList.removeIf(y -> y.age < 23)

);

Stream.of(

new Person(21,"zhangsan"),

new Person(22,"lisi"),

new Person(23,"wangwu"),

new Person(24,"wangwu"),

new Person(23,"lisi"),

new Person(26,"lisi"),

new Person(26,"zhangsan")

).forEach(consumer);

System.out.println(JSON.toJSONString(lisiList));

// 结果 [{"age":23,"name":"lisi"},{"age":26,"name":"lisi"}]

Supplier供给

public List<Integer> getNumList(int num, Supplier<Integer> sup){

List<Integer> list = new ArrayList<>();

for(int i=0;i<num;i++){

Integer a = sup.get();

list.add(a);

}

return list;

}

@Test

public void test2(){

List<Integer> list = getNumList(5,() -> (int)(Math.random()*100));

for(Integer i:list){

System.out.println(i);

}

}

Function函数

public String strHander(String str, Function<String,String> fun){

return fun.apply(str.toLowerCase());

}

@Test

public void test3(){

String str = strHander("Hello world",(t) -> t.replace("o","a"));

System.out.println(str);

}

Predicate策略

public List<String> filterStr(List<String> strs, Predicate<String> pre){

List<String> list = new ArrayList<>();

for(String str:strs){

if(pre.test(str)){

list.add(str);

}

}

return list;

}

@Test

public void test4(){

List<String> list = Arrays.asList("abc","dedff","dde","ccdee","fde");

list = filterStr(list,(x)->x.length()==3);

for(String str:list){

System.out.println(str);

}

}

参考  java8新特性" title="java8新特性">java8新特性

以上是 java8特性之函数式接口 的全部内容, 来源链接: utcz.com/z/517250.html

回到顶部