package com.learn.tang;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.stream.Stream;
class Student {
private String name;
private int age;
private String type;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + ", type=" + type + "]";
}
}
/**
* Consumer、Supplier、Predicate、Function
* <p>
* 这几个接口都在 java.util.function包下的,分别是:
* <ul>
* <li>Consumer(消费型)</li>
* <li>supplier(供给型)</li>
* <li>predicate(谓词型)</li>
* <li>function(功能性)</li>
* </ul>
* Stream相关功能:
* <ul>
* <li>forEach</li>
* <li>sum</li>
* <li>map</li>
* <li>mapToInt</li>
* </ul>
* </p>
*
* @author tang
*
*/
public class Test003 {
public static void updateStudent(Student t, Predicate<Student> p, Consumer<Student> c1, Consumer<Student> c2) {
if (p.test(t)) {
c1.accept(t);
} else {
c2.accept(t);
}
}
public static void main(String[] args) {
List<Student> list = new ArrayList<>();
for (int i = 0; i < 10; ++i) {
final int ii = i;
Supplier<Student> sp = () -> {
return new Student("Join" + Integer.valueOf(ii), 5 + ii);
};
Student o = sp.get();
updateStudent(o, (t) -> t.getAge() >= 10, (t) -> t.setType("person"), (t) -> t.setType("young"));
list.add(o);
}
list.stream().forEach((o) -> System.out.println(o));
int total = list.stream().mapToInt((t) -> t.getAge()).sum();
System.out.println("total age=" + total);
Stream<Student> stream = list.stream();
stream.forEach((o) -> System.out.println(o));
list.stream().map((t) -> t.getName()).map(String::toUpperCase).forEach(System.out::println);
list.stream().mapToInt((t) -> t.getAge()).filter((t) -> t > 10).forEach(System.out::println);
Supplier<String> a = String::new;
String s = a.get();
s = s.concat("hello World!");
System.out.println(s);
}
}
参考地址:https://blog.csdn.net/sihai12345/article/details/99374583
本文标题:Java 8 的 Consumer、Supplier、Predicate和Function
本文链接:https://blog.quwenai.cn/post/8353.html
版权声明:本文不使用任何协议授权,您可以任何形式自由转载或使用。






还没有评论,来说两句吧...