java8新特性(Lambda表达式、四大核心内置对象)
java8新特性的主要表现:
1、Lambda表达式
2、函数式接口
3、方法引用和构造器引用
4、Stream API
5、接口中的默认方法与静态方法
6、新时间日期API
Lambda表达式:
//原来的匿名内部类
@Test
public void test1(){
Comparator<String> com = new Comparator<String>(){
@Override
public int compare(String o1, String o2) {
return Integer.compare(o1.length(), o2.length());
}
};
TreeSet<String> ts = new TreeSet<>(com);
TreeSet<String> ts2 = new TreeSet<>(new Comparator<String>(){
@Override
public int compare(String o1, String o2) {
return Integer.compare(o1.length(), o2.length());
}
});
}
//现在的 Lambda 表达式
@Test
public void test2(){
Comparator<String> com = (x, y) -> Integer.compare(x.length(), y.length());
TreeSet<String> ts = new TreeSet<>(com);
}
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)
);
//需求:获取公司中年龄小于 35 的员工信息
public List<Employee> filterEmployeeAge(List<Employee> emps){
List<Employee> list = new ArrayList<>();
for (Employee emp : emps) {
if(emp.getAge() <= 35){
list.add(emp);
}
}
return list;
}
@Test
public void test3(){
List<Employee> list = filterEmployeeAge(emps);
for (Employee employee : list) {
System.out.println(employee);
}
}
//需求:获取公司中工资大于 5000 的员工信息
public List<Employee> filterEmployeeSalary(List<Employee> emps){
List<Employee> list = new ArrayList<>();
for (Employee emp : emps) {
if(emp.getSalary() >= 5000){
list.add(emp);
}
}
return list;
}
public interface MyPredicate<T> {
public boolean test(T t);
}
public class FilterEmployeeForAge implements MyPredicate<Employee>{
@Override
public boolean test(Employee t) {
return t.getAge() <= 35;
}
}
public class FilterEmployeeForSalary implements MyPredicate<Employee> {
@Override
public boolean test(Employee t) {
return t.getSalary() >= 5000;
}
}
//优化方式一:策略设计模式
public List<Employee> filterEmployee(List<Employee> emps, MyPredicate<Employee> mp){
List<Employee> list = new ArrayList<>();
for (Employee employee : emps) {
if(mp.test(employee)){
list.add(employee);
}
}
return list;
}
@Test
public void test4(){
List<Employee> list = filterEmployee(emps, new FilterEmployeeForAge());
for (Employee employee : list) {
System.out.println(employee);
}
System.out.println("------------------------------------------");
List<Employee> list2 = filterEmployee(emps, new FilterEmployeeForSalary());
for (Employee employee : list2) {
System.out.println(employee);
}
}
//优化方式二:匿名内部类
@Test
public void test5(){
List<Employee> list = filterEmployee(emps, new MyPredicate<Employee>() {
@Override
public boolean test(Employee t) {
return t.getId() <= 103;
}
});
for (Employee employee : list) {
System.out.println(employee);
}
}
//优化方式三:Lambda 表达式
@Test
public void test6(){
List<Employee> list = filterEmployee(emps, (e) -> e.getAge() <= 35);
list.forEach(System.out::println);
System.out.println("------------------------------------------");
List<Employee> list2 = filterEmployee(emps, (e) -> e.getSalary() >= 5000);
list2.forEach(System.out::println);
}
//优化方式四:Stream API
@Test
public void test7(){
emps.stream()
.filter((e) -> e.getAge() <= 35)
.forEach(System.out::println);
System.out.println("----------------------------------------------");
emps.stream()
.map(Employee::getName)
.limit(3)
.sorted()
.forEach(System.out::println);
}
Lambda表达式的基础语法:
->:称为箭头操作符,或者lambda操作符,箭头操作符把表达式拆分成两份
左侧:表达式的参数列表
右侧:表达式需要执行的功能, 即Lambda体
语法格式一:无参数,无返回值 () -> System.out.println("Hello Lambda!");
@Test
public void test1(){
int num = 0;//jdk 1.7 前,必须是 final
Runnable r = new Runnable() {
@Override
public void run() {
System.out.println("Hello World!" + num);
}
};
r.run();
System.out.println("-------------------------------");
Runnable r1 = () -> System.out.println("Hello Lambda!");
r1.run();
}
语法格式二:有一个参数,并且无返回值 (x) -> System.out.println(x)
@Test
public void test2(){
Consumer<String> con = (x) -> System.out.println(x);
con.accept("好好学习,天天向上!");
}
语法格式三:若只有一个参数,小括号可以省略不写 x -> System.out.println(x)
@Test
public void test2(){
Consumer<String> con = x -> System.out.println(x);
con.accept("xxx");
}
语法格式四:有两个以上的参数,有返回值,并且 Lambda 体中有多条语句
@Test
public void test3(){
Comparator<Integer> com = (x, y) -> {
System.out.println("xxxx");
return Integer.compare(x, y);
};
}
语法格式五:若 Lambda 体中只有一条语句, return 和 大括号都可以省略不写
@Test
public void test4(){
Comparator<Integer> com = (x, y) -> Integer.compare(x, y);
}
语法格式六:Lambda 表达式的参数列表的数据类型可以省略不写,因为JVM编译器通过上下文推断出,数据类型,即“类型推断” (Integer x, Integer y) -> Integer.compare(x, y);
@Test
public void test5(){
String[] strs = {"aaa", "bbb", "ccc"};
List<String> list = new ArrayList<>();
show(new HashMap<>());
}
public void show(Map<String, Integer> map){
}
lambda表达式需要函数式接口的支持:
函数式接口:接口中只有一个抽象方法的接口,称为函数式接口,可以使用注解 @FunctionalInterface 修饰,可以检查是否是函数式接口
@FunctionalInterface
public interface Fun {
public Integer getValue(Integer num);
}
//需求:对一个数进行运算
@Test
public void test6(){
Integer num = operation(100, (x) -> x * x);
System.out.println(num);
System.out.println(operation(200, (y) -> y + 200));
}
public Integer operation(Integer num, Fun mf){
return mf.getValue(num);
}
//比较两个实体,先按照年龄比较,相同则按照姓名比较
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)
);
@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);
}
}
//字符串操作
@FunctionalInterface
public interface MyFunction {
public String getValue(String str);
}
//需求:用于处理字符串
public String strHandler(String str, MyFunction mf){
return mf.getValue(str);
}
@Test
public void test2(){
String trimStr = strHandler("\t\t\tjava天下第一 ", (str) -> str.trim());
System.out.println(trimStr);
String upper = strHandler("abcdef", (str) -> str.toUpperCase());
System.out.println(upper);
String newStr = strHandler("PHP天下第一", (str) -> str.substring(2, 5));
System.out.println(newStr);
}
public interface MyFunction2<T, R> {
public R getValue(T t1, T t2);
}
//需求:对于两个 Long 型数据进行处理
public void op(Long l1, Long l2, MyFunction2<Long, Long> mf){
System.out.println(mf.getValue(l1, l2));
}
@Test
public void test3(){
op(100L, 200L, (x, y) -> x + y);
op(100L, 200L, (x, y) -> x * y);
}
、
java8中内置的四大函数式接口
Customer<T> 消费型接口
void accept( T t);
//Consumer<T> 消费型接口 :
@Test
public void test1(){
happy(10000, (m) -> System.out.println("此次购物消费" + m + "元"));
}
public void happy(double money, Consumer<Double> con){
con.accept(money);
}
Supplier( T t ) 供给型接口
T get();
//Supplier<T> 供给型接口 :
@Test
public void test2(){
List<Integer> numList = getNumList(10, () -> (int)(Math.random() * 100));
for (Integer num : numList) {
System.out.println(num);
}
}
//需求:产生指定个数的整数,并放入集合中
public List<Integer> getNumList(int num, Supplier<Integer> sup){
List<Integer> list = new ArrayList<>();
for (int i = 0; i < num; i++) {
Integer n = sup.get();
list.add(n);
}
return list;
}
Function<T, R>:函数型接口
R apply(T t);
//Function<T, R> 函数型接口:
@Test
public void test3(){
String newStr = strHandler("\t\t\t 我大尚硅谷威武 ", (str) -> str.trim());
System.out.println(newStr);
String subStr = strHandler("我大尚硅谷威武", (str) -> str.substring(2, 5));
System.out.println(subStr);
}
//需求:用于处理字符串
public String strHandler(String str, Function<String, String> fun){
return fun.apply(str);
}
Predicate<T>:断言型接口
boolean test(T t);
//Predicate<T> 断言型接口:
@Test
public void test4(){
List<String> list = Arrays.asList("java", "php", "android", "ios", ".net");
List<String> strList = filterStr(list, (s) -> s.length() > 4);
for (String str : strList) {
System.out.println(str);
}
}
//需求:将满足条件的字符串,放入集合中
public List<String> filterStr(List<String> list, Predicate<String> pre){
List<String> strList = new ArrayList<>();
for (String str : list) {
if(pre.test(str)){
strList.add(str);
}
}
return strList;
}