Lambda结合函数式接口练习
Posted Java码农社区
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Lambda结合函数式接口练习相关的知识,希望对你有一定的参考价值。
package com.chentongwei.java8.day01;
public class Employee {
private Integer id;
private String name;
private int age;
private double salary;
public Employee(String name, int age, double salary) {
super();
this.name = name;
this.age = age;
this.salary = salary;
}
public Employee() {
super();
}
public Employee(Integer id, String name, int age, double salary) {
super();
this.id = id;
this.name = name;
this.age = age;
this.salary = salary;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
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 double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
@Override
public String toString() {
return "Employee [name=" + name + ", age=" + age + ", salary=" + salary + "]";
}
}
package com.chentongwei.java8.day03;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.junit.Test;
import com.chentongwei.java8.day01.Employee;
/**
* Lambda表达式结合函数式接口练习
* @author TongWei.Chen
* @date 2017年3月31日22:31:02
*/
public class TestLambdaFun {
List<Employee> emps = Arrays.asList(
new Employee(101, "张三", 18, 9999.99),
new Employee(102, "李四", 59, 6666.66),
new Employee(103, "王五", 28, 3333.33),
new Employee(104, "赵六", 8, 7777.77),
new Employee(105, "田七", 38, 5555.55)
);
}
练习1:调用Collections.sort()方法,通过制定排序比较两个Employee(先按照年龄比,年龄相同按姓名比),使用Lambda作为参数传递
@Test
public void test1() {
Collections.sort(emps, (e1, e2) -> {
if(e1.getAge() == e2.getAge()) {
return e1.getName().compareTo(e2.getName());
} else {
return Integer.compare(e1.getAge(), e2.getAge());
}
});
for (Employee emp : emps) {
System.out.println(emp);
}
}
练习2
①声明函数式接口,接口中声明抽象方法,public String getVlaue(String str);
②编写方法使用接口作为参数,将字符串转换成大写,并作为方法的返回值。
③再将一个字符串的第2个和第4个索引位置进行截取字符串。
package com.chentongwei.java8.day03;
@FunctionalInterface
public interface MyFun {
String getValue(String str);
}
@Test
public void test2() {
String str1 = getValue("hello world", str -> str.toUpperCase());
System.out.println("转换成大写后:" + str1);
String str2 = getValue("hello world", str -> str.substring(2, 4));
System.out.println("截取后的字符串是:" + str2);
}
public String getValue(String str, MyFun fun) {
return fun.getValue(str);
}
练习3:
①声明一个带两个泛型的函数式接口,泛型类型为<T,R>,T为参数,R为返回值
②接口中声明对应的抽象方法
③声明测试方法没使用接口作为参数,计算两个long类型参数的和
④在计算两个long类型参数的乘积
package com.chentongwei.java8.day03;
@FunctionalInterface
public interface MyFun2<T, R> {
R getValue(T t1, T t2);
}
@Test
public void test3() {
getValue(100L, 100L, (num1, num2) -> num1 + num2);
getValue(100L, 100L, (num1, num2) -> num1 * num2);
}
public void getValue(long num1, long num2, MyFun2<Long, Long> fun2) {
System.out.println(fun2.getValue(num1, num2));
}
以上是关于Lambda结合函数式接口练习的主要内容,如果未能解决你的问题,请参考以下文章