java基础---java8 新特性

时间:2023-03-09 19:25:33
java基础---java8 新特性

1. 函数式接口

  • 函数式接口主要指只包含一个抽象方法的接口,如:java.lang.Runnable(java1.0)、java.util.Comparator接口(java1.4)等。
  • Java8提供@FunctionalInterface注解来定义函数式接口,若定义的接口不符合函数式的规范便会报错
  • java.util.function包包含了常用的函数式接口
接口名称 方法声明 功能介绍
Consumer void accept(T t) 根据指定的参数执行操作
Supplier T get() 得到一个返回值
Function<T,R> R apply(T t) 根据指定的参数执行操作并返回
Predicate boolean test(T t) 判断指定的参数是否满足条件

2. lambda表达式

  • 语法格式:(参数列表) -> { 方法体; } - 其中()、参数类型、{} 以及return关键字 可以省略

3.方法引用

  • 通过方法的名字来指向一个方法而不需要为方法引用提供方法体,该方法的调用交给函数式接口执行
  • 方法引用使用一对冒号 :: 将类或对象与方法名进行连接,通常使用方式如下:
    • 对象的非静态方法引用 ObjectName :: MethodName
    • 类的静态方法引用 ClassName :: StaticMethodName
    • 类的非静态方法引用 ClassName :: MethodName
    • 构造器的引用 ClassName :: new
    • 数组的引用 TypeName[] :: new
  • 方法引用是在特定场景下lambda表达式的一种简化表示,可以进一步简化代码的编写使代码更加紧凑简洁,从而减少冗余代码
package task02;

import java.util.Comparator;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier; public class Java8New {
public static void main(String[] args) {
//函数式接口
Comparator comparator = new Comparator() {
@Override
public int compare(Object o1, Object o2) {
return -1;
}
};
System.out.println(comparator.compare(1, 2));
System.out.println("---------------");
Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println("running");
}
};
runnable.run();
System.out.println("---------------");
Consumer consumer = new Consumer() {
@Override
public void accept(Object o) {
System.out.println(o);
}
};
consumer.accept("函数式接口");
System.out.println("---------------");
Supplier supplier = new Supplier() {
@Override
public Object get() {
return "返回单个值";
}
};
System.out.println(supplier.get());
System.out.println("---------------");
Function function = new Function() {
@Override
public Object apply(Object o) {
return o;
}
};
System.out.println(function.apply("指定参数返回"));
System.out.println("---------------");
Predicate predicate = new Predicate() {
@Override
public boolean test(Object o) {
return false;
}
};
System.out.println(predicate.test("不满足条件"));
//lambda表达式
System.out.println("***************");
Comparator comparator1 = (Object o1, Object o2) -> -1;
System.out.println(comparator.compare(2, 3));
System.out.println("***************");
Runnable runnable1 = () -> System.out.println("running");
runnable1.run();
System.out.println("***************");
Consumer consumer1 = o -> System.out.println(o);
consumer1.accept("函数式接口");
System.out.println("***************");
Supplier supplier1 = () -> "返回单个值";
System.out.println(supplier.get());
System.out.println("***************");
Function function1 = o1 -> o1;
System.out.println(function1.apply("hello"));
System.out.println("***************");
Predicate predicate1 = o -> false;
System.out.println(predicate1.test("false")); //方法引用
System.out.println("======================");
Person person = new Person("hello");
Consumer<String> consumer2= person::setName;
consumer2.accept("zhangfei");
System.out.println(person.getName());
System.out.println("======================");
Supplier<String> supplier2=person::getName;
System.out.println(supplier2.get());
System.out.println("======================");
Function<String,Integer> function2=Integer::parseInt;
System.out.println(function2.apply("12345"));
System.out.println("======================");
Function<String,Person> function3=Person::new;
System.out.println(function3.apply("guanyu").getName());
System.out.println("======================");
Function<Integer,Integer[]>function4=Integer[]::new;
Integer[] apply = function4.apply(4);
for (Integer i:apply) {
System.out.println(i);
}
} }

4. Stream接口

  • java.util.stream.Stream接口是对集合功能的增强,可以对集合元素进行复杂的查找、过滤、筛选操作
  • 借助于Lambda 表达式极大的提高编程效率和程序可读性,同时它提供串行和并行两种模式进行汇聚操作,并发模式能够充分利用多核处理器的优势
  • 创建
    • 方式一:通过调用集合的默认方法来获取流,如:default Stream stream()
    • 方式二:通过数组工具类中的静态方法来获取流,如:static IntStream stream(int[] array)
    • 方式三:通过Stream接口的静态方法来获取流,如:static Stream of(T... values)
    • 方式四:通过Stream接口的静态方法来获取流,static Stream generate(Supplier<? extends T> s)
  • 筛选切片
方法声明 功能介绍
Stream filter(Predicate<? super T> predicate) 返回一个包含匹配元素的流
Stream distinct() 返回不包含重复元素的流
Stream limit(long maxSize) 返回不超过给定元素数量的流
Stream skip(long n) 返回丢弃前n个元素后的流
  • 映射
方法声明 功能介绍
Stream map(Function<? super T,? extends R>
mapper)
返回每个处理过元素组成的流
Stream flatMap(Function<? super T,? extends
Stream<? extends R>> mapper)
返回每个被替换过元素组成的流,并
将所有流合成一个流
  • 排序
方法声明 功能介绍
Stream sorted() 返回经过自然排序后元素组成的流
Stream sorted(Comparator<? super T> comparator) 返回经过比较器排序后元素组成的流
  • 匹配与查找
方法声明 功能介绍
Optional findFirst() 返回该流的第一个元素
boolean allMatch(Predicate<? super T> predicate) 返回所有元素是否匹配
boolean noneMatch(Predicate<? super T> predicate) 返回没有元素是否匹配
Optional max(Comparator<? super T> comparator) 根据比较器返回最大元素
Optional min(Comparator<? super T> comparator) 根据比较器返回最小元素
long count() 返回元素的个数
void forEach(Consumer<? super T> action) 对流中每个元素执行操作
  • 规约:
    Optional reduce(BinaryOperator accumulator) 返回结合后的元素值
  • 收集:
    <R,A> R collect(Collector<? super T,A,R> collector) 使用收集器对元素进行处理
package task02;

import java.util.ArrayList;
import java.util.List;
import java.util.function.BinaryOperator;
import java.util.stream.Collectors;
import java.util.stream.Stream; public class StreamTest {
public static void main(String[] args) {
List<Person> list = new ArrayList<>();
list.add(new Person("zhangfei", 30));
list.add(new Person("wangfei", 18));
list.add(new Person("lifei", 29));
list.add(new Person("sunfei", 25));
list.add(new Person("qianfei", 15));
list.add(new Person("zhaofei", 42));
list.add(new Person("zhangfei", 30)); //创建Stream
Stream<Person> stream = list.stream(); //操作
//Stream filter(Predicate<? super T> predicate) 返回一个包含匹配元素的流
stream.filter((Person person) -> {
return person.getAge() > 20;
}).forEach((Person person) -> System.out.println(person));
System.out.println("--------------");
//Stream distinct() 返回不包含重复元素的流
list.stream().distinct().forEach((Person person) -> System.out.println(person));
System.out.println("--------------");
//Stream skip(long n) 返回丢弃前n个元素后的流
//Stream limit(long maxSize) 返回不超过给定元素数量的流
//丢弃前2个返回后四个
list.stream().skip(2).limit(4).forEach((Person person) -> System.out.println(person));
System.out.println("--------------");
//方法声明 功能介绍
//Stream map(Function<? super T,? extends R> mapper) 返回每个处理过元素组成的流
list.stream().map(person -> person.getName()).forEach((String s) -> System.out.println(s));
//Optional findFirst() 返回该流的第一个元素
System.out.println(list.stream().findFirst());
//boolean noneMatch(Predicate<? super T> predicate) 返回没有元素是否匹配
System.out.println(list.stream().noneMatch(person -> person.getAge() > 25));
//方法声明 功能介绍
//Optional reduce(BinaryOperator accumulator) 返回结合后的元素值
System.out.print("sum");
System.out.println(list.stream().map((Person::getAge)).reduce((o1, o2) -> o1 + o2));
//方法声明 功能介绍
//<R,A> R collect(Collector<? super T,A,R> collector) 使用收集器对元素进行处理
list.stream().collect(Collectors.toList()).forEach((Person person) -> System.out.println(person));
}
}

5. Optional类的使用

  • java.util.Optional类可以理解为一个简单的容器,其值可能是null或者不是null,代表一个值存在或不存在。该类的引入很好的解决空指针异常,不用显式进行空值检测。
方法声明 功能介绍
static Optional ofNullable(T value) 根据参数指定数值来得到Optional类型的对
Optional map(Function<? super T,? extends U>
mapper)
根据参数指定规则的结果来得到Optional类
型的对象
T orElse(T other) 若该值存在就返回,否则返回other的数
package task02;

import java.util.Optional;

public class OptionalTest {
public static void main(String[] args) {
//判断字符串是否为空,若不为空则打印字符串的长度,否则打印0
String s = "hello";
Optional<String> s1 = Optional.ofNullable(s);
System.out.println(s1.orElse("0"));//hello String s2 = null;
Optional<String> s3 = Optional.ofNullable(s2);
System.out.println(s3.orElse("0")); //0
}
}

相关文章