https://www.cnblogs.com/CobwebSong/p/9593313.html
https://www.cnblogs.com/linzhanfly/p/9686941.html
I. Overview
name | type | description |
---|---|---|
Consumer | Consumer< T > | Receiving the object T, does not return value |
Predicate | Predicate< T > | Receiving the object and returns a boolean T |
Function | Function< T, R > | T receiving object, and returns the object R |
Supplier | Supplier< T > | Providing an object T (e.g. plant) does not receive a value |
UnaryOperator | UnaryOperator< T > | T receiving object, and returns the object T |
BiConsumer | BiConsumer<T, U> | T and U receiving objects objects, does not return value |
BiPredicate | BiPredicate<T, U> | T and U receiving objects objects, returns a boolean |
BiFunction | BiFunction<T, U, R> | T and U objects receiving object, and returns the object R |
BinaryOperator | BinaryOperator< T > | T receives two objects, the object returns T |
Reference: https: //blog.csdn.net/huo065000/article/details/78964382
Two Consumer
1 role
- An object of consumption
2 Use Scene
- Iterable forEach methods of the interface need to pass Consumer, most of the collection classes implement this interface is used to return an Iterator object to iterate.
3 design ideas
- When the developer calls ArrayList.forEach, generally desirable custom logic traversal consumption, such as: a log output or operation processing.
- Processing logic left to the user, the use of flexible.
- Changing logic can be packaged into a class (Consumer implement the interface), the logic extract .
PASS: Javascript able to function to another function, this should be reflected in a functional programming, java class of function package is similar.
public interface Iterable<T> { default void forEach(Consumer<? super T> action) { Objects.requireNonNull(action); for (T t : this) { action.accept(t); } } }
4 DEMO
public class ConsumerTest {
public static void main(String[] args) { ArrayList<Employee> employees = new ArrayList<>(); String[] prefix = {"A", "B"}; for (int i = 1; i <= 10; i++) employees.add(new Employee(prefix[i % 2] + i, i * 1000)); employees.forEach(new SalaryConsumer()); employees.forEach(new NameConsumer()); } static class Employee { private String name; private int salary; public Employee() { this.salary = 4000; } public Employee(String name, int salary) { this.name = name; this.salary = salary; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getSalary() { return salary; } public void setSalary(int salary) { this.salary = salary; } @Override public String toString() { return new StringBuilder() .append("name:").append(name) .append(",salary:").append(salary) .toString(); } } // 输出需要交税的员工 static class SalaryConsumer implements Consumer<Employee> { @Override public void accept(Employee employee) { if (employee.getSalary() > 2000) { System.out.println(employee.getName() + "要交税了."); } } } // 输出需要名字前缀是‘A’的员工信息 static class NameConsumer implements Consumer<Employee> { @Override public void accept(Employee employee) { if (employee.getName().startsWith("A")) { System.out.println(employee.getName() + " salary is " + employee.getSalary()); } } } }
三 Predicate
1 role
- Determine whether the objects that meet certain criteria
2 Use Scene
ArrayList of removeIf (Predicate): Delete meet the conditions of the elements
If the conditions are hard-coded in the ArrayList, it will provide numerous implementations, but if conditions allow incoming caller, so ArrayList can be freed from the complex, and can not guess the business.
3 design ideas
- Extraction conditions , so that the conditions departing from the processing logic, decoupling
4 DEMO
// employee.getSalary() > 2000 提取成一个条件类
class SalaryConsumer implements Consumer<Employee> { @Override public void accept(Employee employee) { // 自行传入本地的最低交税工资 if (new SalaryPredicate(2000).test(employee)) { System.out.println(employee.getName() + "要交税了."); } } } class SalaryPredicate implements Predicate<Employee>{ private int tax; public SalaryPredicate(int tax) { this.tax = tax; } @Override public boolean test(Employee employee) { return employee.getSalary() > tax; } }
Three Function
1 role
- To achieve a "single functions", i.e. passing through a calculation function return value to another value.
2 Use Scene
- V HashMap.computeIfAbsent (K, Function <K, V>) // simplified code if the key has not been assigned a value associated with or associated with a null, the function returns the value used alternatively.
- <R> Stream<R> map(Function<? super T, ? extends R> mapper); // 转换流
3 design ideas
- Thought of functions of one variable, the conversion logic is extracted, decoupled
4 DEMO
public static void main(String[] args) { ArrayList<Employee> employees = new ArrayList<>(); String[] prefix = {"B", "A"}; for (int i = 1; i <= 10; i++) employees.add(new Employee(prefix[i % 2] + i, i * 1000)); int[] expenses = ListToArray(employees, new EmployeeToExpenses());// 公司对单个员工的支出数组 int[] incomes = ListToArray(employees, new EmployeeToIncome()); // 单个员工的收入数组 System.out.println("社保+公积金+税=" + (sum(expenses) - sum(incomes)) + "元"); } private static int[] ListToArray(List<Employee> list, Function<Employee, Integer> function) { int[] ints = new int[list.size()]; for (int i = 0; i < ints.length; i++) ints[i] = function.apply(list.get(i)); return ints; } private static int sum(int[] salarys) { int sum = 0; for (int i = 0; i < salarys.length; i++) sum += salarys[i]; return sum; } // 公司支出 static class EmployeeToExpenses implements Function<Employee, Integer> { @Override public Integer apply(Employee employee) { // 假设公司公积金和社保为工资的20% return Double.valueOf(employee.getSalary() * (1 + 0.2)).intValue(); } } // 员工实际到手工资 static class EmployeeToIncome implements Function<Employee, Integer> { @Override public Integer apply(Employee employee) { // 假设员工薪水 * 80% 为到手工资 return Double.valueOf(employee.getSalary() * (1 - 0.2)).intValue(); } }
Four Supplier
1 role
- Create an object (factory class)
2 Use Scene
- Optional.orElseGet (Supplier <extends T?>): When this object is created by passing a supplier is null T returns.
3 design ideas
- Packaging factory creates logical objects
4 DEMO
public static void main(String[] args) { // 生成固定工资的员工 Supplier<Employee> supplier = () -> new Employee(); Employee employee1 = supplier.get(); employee1.setName("test1"); Employee employee2 = supplier.get(); employee2.setName("test2"); System.out.println("employee1:" + employee1); System.out.println("employee2:" + employee2); }
Five UnaryOperator
1 role
- UnaryOperator inherited Function, Role and Function same
- However UnaryOperator, defining the passed type and return type necessarily the same
2 Use Scene
- List.replaceAll (UnaryOperator) // list of all the elements of the clearing operation is replaced element
- Stream.iterate (T, UnaryOperator) // Repeat call UnaryOperator seed to generate elements
3 design ideas
- Thought of functions of one variable, the same conversion logic is extracted, decoupled
4 DEMO
public static void main(String[] args) { ArrayList<Employee> employees = new ArrayList<>(); String[] prefix = {"B", "A"}; for (int i = 1; i <= 10; i++) employees.add(new Employee(prefix[i % 2] + i, i * 1000)); System.o ut.println("公司进行薪资调整..."); salaryAdjustment(employees,new SalaryAdjustment(4000)); employees.forEach(System.out::println); } static void salaryAdjustment(List<Employee> list, UnaryOperator<Employee> operator) { for (int i = 0; i < list.size(); i++) { list.set(i, operator.apply(list.get(i))); } } static class SalaryAdjustment implements UnaryOperator<Employee> { private int salary; public SalaryAdjustment(int salary) { this.salary = salary; } @Override public Employee apply(Employee employee) { employee.setSalary(salary); return employee; } }
I. Overview
name | type | description |
---|---|---|
Consumer | Consumer< T > | Receiving the object T, does not return value |
Predicate | Predicate< T > | Receiving the object and returns a boolean T |
Function | Function< T, R > | T receiving object, and returns the object R |
Supplier | Supplier< T > | Providing an object T (e.g. plant) does not receive a value |
UnaryOperator | UnaryOperator< T > | T receiving object, and returns the object T |
BiConsumer | BiConsumer<T, U> | T and U receiving objects objects, does not return value |
BiPredicate | BiPredicate<T, U> | T and U receiving objects objects, returns a boolean |
BiFunction | BiFunction<T, U, R> | T and U objects receiving object, and returns the object R |
BinaryOperator | BinaryOperator< T > | T receives two objects, the object returns T |
Reference: https: //blog.csdn.net/huo065000/article/details/78964382
Two Consumer
1 role
- An object of consumption
2 Use Scene
- Iterable forEach methods of the interface need to pass Consumer, most of the collection classes implement this interface is used to return an Iterator object to iterate.
3 design ideas
- When the developer calls ArrayList.forEach, generally desirable custom logic traversal consumption, such as: a log output or operation processing.
- Processing logic left to the user, the use of flexible.
- Changing logic can be packaged into a class (Consumer implement the interface), the logic extract .
PASS: Javascript able to function to another function, this should be reflected in a functional programming, java class of function package is similar.
public interface Iterable<T> { default void forEach(Consumer<? super T> action) { Objects.requireNonNull(action); for (T t : this) { action.accept(t); } } }
4 DEMO
public class ConsumerTest {
public static void main(String[] args) { ArrayList<Employee> employees = new ArrayList<>(); String[] prefix = {"A", "B"}; for (int i = 1; i <= 10; i++) employees.add(new Employee(prefix[i % 2] + i, i * 1000)); employees.forEach(new SalaryConsumer()); employees.forEach(new NameConsumer()); } static class Employee { private String name; private int salary; public Employee() { this.salary = 4000; } public Employee(String name, int salary) { this.name = name; this.salary = salary; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getSalary() { return salary; } public void setSalary(int salary) { this.salary = salary; } @Override public String toString() { return new StringBuilder() .append("name:").append(name) .append(",salary:").append(salary) .toString(); } } // 输出需要交税的员工 static class SalaryConsumer implements Consumer<Employee> { @Override public void accept(Employee employee) { if (employee.getSalary() > 2000) { System.out.println(employee.getName() + "要交税了."); } } } // 输出需要名字前缀是‘A’的员工信息 static class NameConsumer implements Consumer<Employee> { @Override public void accept(Employee employee) { if (employee.getName().startsWith("A")) { System.out.println(employee.getName() + " salary is " + employee.getSalary()); } } } }
三 Predicate
1 role
- Determine whether the objects that meet certain criteria
2 Use Scene
ArrayList of removeIf (Predicate): Delete meet the conditions of the elements
If the conditions are hard-coded in the ArrayList, it will provide numerous implementations, but if conditions allow incoming caller, so ArrayList can be freed from the complex, and can not guess the business.
3 design ideas
- Extraction conditions , so that the conditions departing from the processing logic, decoupling
4 DEMO
// employee.getSalary() > 2000 提取成一个条件类
class SalaryConsumer implements Consumer<Employee> { @Override public void accept(Employee employee) { // 自行传入本地的最低交税工资 if (new SalaryPredicate(2000).test(employee)) { System.out.println(employee.getName() + "要交税了."); } } } class SalaryPredicate implements Predicate<Employee>{ private int tax; public SalaryPredicate(int tax) { this.tax = tax; } @Override public boolean test(Employee employee) { return employee.getSalary() > tax; } }
Three Function
1 role
- To achieve a "single functions", i.e. passing through a calculation function return value to another value.
2 Use Scene
- V HashMap.computeIfAbsent (K, Function <K, V>) // simplified code if the key has not been assigned a value associated with or associated with a null, the function returns the value used alternatively.
- <R> Stream<R> map(Function<? super T, ? extends R> mapper); // 转换流
3 design ideas
- Thought of functions of one variable, the conversion logic is extracted, decoupled
4 DEMO
public static void main(String[] args) { ArrayList<Employee> employees = new ArrayList<>(); String[] prefix = {"B", "A"}; for (int i = 1; i <= 10; i++) employees.add(new Employee(prefix[i % 2] + i, i * 1000)); int[] expenses = ListToArray(employees, new EmployeeToExpenses());// 公司对单个员工的支出数组 int[] incomes = ListToArray(employees, new EmployeeToIncome()); // 单个员工的收入数组 System.out.println("社保+公积金+税=" + (sum(expenses) - sum(incomes)) + "元"); } private static int[] ListToArray(List<Employee> list, Function<Employee, Integer> function) { int[] ints = new int[list.size()]; for (int i = 0; i < ints.length; i++) ints[i] = function.apply(list.get(i)); return ints; } private static int sum(int[] salarys) { int sum = 0; for (int i = 0; i < salarys.length; i++) sum += salarys[i]; return sum; } // 公司支出 static class EmployeeToExpenses implements Function<Employee, Integer> { @Override public Integer apply(Employee employee) { // 假设公司公积金和社保为工资的20% return Double.valueOf(employee.getSalary() * (1 + 0.2)).intValue(); } } // 员工实际到手工资 static class EmployeeToIncome implements Function<Employee, Integer> { @Override public Integer apply(Employee employee) { // 假设员工薪水 * 80% 为到手工资 return Double.valueOf(employee.getSalary() * (1 - 0.2)).intValue(); } }
Four Supplier
1 role
- Create an object (factory class)
2 Use Scene
- Optional.orElseGet (Supplier <extends T?>): When this object is created by passing a supplier is null T returns.
3 design ideas
- Packaging factory creates logical objects
4 DEMO
public static void main(String[] args) { // 生成固定工资的员工 Supplier<Employee> supplier = () -> new Employee(); Employee employee1 = supplier.get(); employee1.setName("test1"); Employee employee2 = supplier.get(); employee2.setName("test2"); System.out.println("employee1:" + employee1); System.out.println("employee2:" + employee2); }
Five UnaryOperator
1 role
- UnaryOperator inherited Function, Role and Function same
- However UnaryOperator, defining the passed type and return type necessarily the same
2 Use Scene
- List.replaceAll (UnaryOperator) // list of all the elements of the clearing operation is replaced element
- Stream.iterate (T, UnaryOperator) // Repeat call UnaryOperator seed to generate elements
3 design ideas
- Thought of functions of one variable, the same conversion logic is extracted, decoupled
4 DEMO
public static void main(String[] args) { ArrayList<Employee> employees = new ArrayList<>(); String[] prefix = {"B", "A"}; for (int i = 1; i <= 10; i++) employees.add(new Employee(prefix[i % 2] + i, i * 1000)); System.o ut.println("公司进行薪资调整..."); salaryAdjustment(employees,new SalaryAdjustment(4000)); employees.forEach(System.out::println); } static void salaryAdjustment(List<Employee> list, UnaryOperator<Employee> operator) { for (int i = 0; i < list.size(); i++) { list.set(i, operator.apply(list.get(i))); } } static class SalaryAdjustment implements UnaryOperator<Employee> { private int salary; public SalaryAdjustment(int salary) { this.salary = salary; } @Override public Employee apply(Employee employee) { employee.setSalary(salary); return employee; } }