Java 8 API提供了很多全新的函数式接口来让工作更加方便,有一些接口是来自Google Guava库里的,即便你对这些很熟悉了,还是有必要看看这些是如何扩展到lambda上使用的。
一、Optional接口
1、null 带来的种种问题
1)、它是错误之源:NullPointException 是目前Java程序开发中最典型的异常;
2)、它会使你的代码膨胀:它是让你的代码充斥着深度嵌套的null检查,代码的可读性槽糕透顶。
3)、它自身是毫无意义的。null自身没有任何的意义,尤其是,它代表的是静态类型语言中以一种错误的方式对缺失变量值得建模。
4)、它破坏了Java的哲学。Java一直试图避免让程序员意识到指针的存在,唯一的例外是:null指针。
5)、它是Java的类型系统上开了个口子:null并不属于任何类型,这意味着它可以被赋予值给任意引用类型的变量。这会导致问题,原因是当这个变量被传递到系统中的另外一个部分后,你将无法获知这个null变量最初的赋值到底是什么类型。
2、初识Optional
**Optional 不是函数是接口,这是个用来防止NullPointerException异常的辅助类型,这是下一届中将要用到的重要概念,现在先简单的看看这个接口能干什么:
Optional 被定义为一个简单的容器,其值可能是null或者不是null。在Java 8之前一般某个函数应该返回非空对象但是偶尔却可能返回了null,而在Java 8中,不推荐你返回null而是返回Optional。**
3、使用map
**Optional<Insurance> optInsurance = Optional.ofNullable(insurance);
Optional<String> name = optInsurance.map(Insurance::getName);
你可以把Optional对象看成一种特殊的集合数据,它至多包含一个元素。如果Optional包含一个值,那函数就将该值作为参数传递给map,对该值进行转换。如果Optional为空,就什么也不做。**
3、使用flatMap
存在这样的变态代码:person.getCar().getInsurance().getName();
非空判断一定很伤心,使用flatmap轻松解决:person.flatMap(Person::getCar).flatMap(Car::getInsurance) .map(Insurance::getName).orElse("Unknown");
4、解引用Optional 对象
我们决定采用orElse方法读取这个变量的值,使用这种方式你还可以定义一个默认值,遭遇空的Optional变量时,默认值会作为该方法的调用返回值。Optional类提供了多种方法读取Optional实例中的变量值。
get()是这些方法中最简单但又最不安全的方法。如果变量存在,它直接返回封装的变量值,否则就抛出一个NoSuchElementException异常。
orElse(T other)允许你在Optional对象不包含值时提供一个默认值。
orElseGet(Supplier<? extends T> other)是orElse方法的延迟调用版,Supplier方法只有在Optional对象不含值时才执行调用。
orElseThrow(Supplier<? extends X> exceptionSupplier)和get方法非常类似,它们遭遇Optional对象为空时都会抛出一个异常,但是使用orElseThrow你可以定制希望抛出的异常类型。
ifPresent(Consumer<? super T>)让你能在变量值存在时执行一个作为参数传入的方法,否则就不进行任何操作。
5、 Optional类的方法
方法 | 描述 |
---|---|
empty | 返回一个optional实例 |
filter | 如果值存在并且满足提供的谓词,就返回包含该值的optional对象;否则返回个空的optional对象 |
faltMap | 如果值存在,就对该值执行提供的mapping函数调用,返回一个optional类型的值。否则返回一个空的optional对象 |
get | 如果该值存在,就对该值用optional封装返回,否则抛出一个NoSunchElementException异常 |
ifPresent | 如果值存在,就执行使用该值的方法调用,否则什么也不做 |
isPresent | 如果该值存在就返回true,否则返回false |
map | 如果该值存在,就对该值执行提供的mapping函数调用 |
map | 将指定值的optional封装之后返回,如果该值为null,则会抛出一个NullPointerException异常 |
ofNullable | 将指定值用optional封装之后返回,如果返回为null,则返回个空的optional对象 |
ofElse | 如果有值则将其返回,否则返回一个默认值 |
ofElseGet | 如果有值则将其返回,否则返回一个由指定的supplier接口生成的值 |
ofElseThrow | 如果有值则将其返回,否则返回一个由指定的supplier接口生成的异常 |
import java.util.Optional;
public class Test {
public static void main(String[] args) {
Optional<String> optional = Optional.of("hello world");
optional.isPresent(); // true
optional.get(); // "hello world"
optional.orElse("fall back"); // "hello world"
System.out.println("optional.isPresent() :" + optional.isPresent());
System.out.println("optional.get() :" + optional.get());
System.out.println("optional.orElse('fall back') :" + optional.orElse("fall back"));
optional.ifPresent((s) -> System.out.println(s.charAt(0))); // "h"
}
}
二、Predicate 接口
Predicate 接口只有一个参数,返回boolean类型。该接口包含多种默认方法来将Predicate组合成其他复杂的逻辑(比如:与,或,非):
import java.util.function.Predicate;
public class Test {
public static void main(String[] args) {
Predicate<String> predicate = (s) -> s.length() > 0;
predicate.test("foo"); // true
predicate.negate().test("foo"); // false
System.out.println("predicate.test('foo') :" + predicate.test("foo"));
System.out.println("predicate.negate().test('foo') :" + predicate.negate().test("foo"));
}
}
三、Function 接口
Function 接口有一个参数并且返回一个结果,并附带了一些可以和其他函数组合的默认方法(compose, andThen
import java.util.function.Function;
public class Test {
public static void main(String[] args) {
Function<String, Integer> toInteger = Integer::valueOf;
Function<String, String> backToString = toInteger.andThen(String::valueOf);
backToString.apply("123"); // "123"
System.out.println("backToString.apply('123') :" + backToString.apply("123"));
}
}
四、Supplier 接口
Supplier 接口返回一个任意范型的值,和Function接口不同的是该接口没有任何参数
$\color{red}{示例代码常用类}$
import lombok.Data;
@Data
public class User implements Serializable{
private static final long serialVersionUID = 1L;
private String name;
private String adress;
}
Supplier 接口示例
import java.util.function.Supplier;
import com.test.dao.User;
public class Test {
public static void main(String[] args) {
Supplier<User> personSupplier = User::new;
personSupplier.get(); // new Person
System.out.println("personSupplier.get() :" + personSupplier.get());
}
}
五、Consumer 接口
Consumer 接口表示执行在单个参数上的操作。
import java.util.function.Consumer;
import com.test.dao.User;
public class Test {
public static void main(String[] args) {
Consumer<User> greeter = (u) -> System.out.println("Hello, " + u.getName()); //"Hello, LiSi"
greeter.accept(new User("LiSi", "ShenZhen"));
}
}
六、Comparator 接口
Comparator 是老Java中的经典接口, Java 8在此之上添加了多种默认方法:
import java.util.Comparator;
import com.test.dao.User;
public class Test {
public static void main(String[] args) {
Comparator<User> comparator = (p1, p2) -> p1.getName().compareTo(p2.getName());
User p1 = new User("WangWu", "BeiJing");
User p2 = new User("MaLiu", "ShangHai");
comparator.compare(p1, p2); // > 0 (comparator.compare(p1, p2) :10)
comparator.reversed().compare(p1, p2); // < 0 (comparator.reversed().compare(p1, p2) :-10)
System.out.println("comparator.compare(p1, p2) :" + comparator.compare(p1, p2));
System.out.println("comparator.reversed().compare(p1, p2) :" + comparator.reversed().compare(p1, p2));
}
}
六、Stream 接口
java.util.Stream 表示能应用在一组元素上一次执行的操作序列。Stream 操作分为中间操作或者最终操作两种,最终操作返回一特定类型的计算结果,而中间操作返回Stream本身,这样你就可以将多个操作依次串起来。Stream 的创建需要指定一个数据源,比如 java.util.Collection的子类,List或者Set, Map不支持。Stream的操作可以串行执行或者并行执行。
$\color{red}{可以通过 Collection.stream() 或者 Collection.parallelStream() 来创建一个Stream,详细资料在二、Stream API已经阐述}$
七、Filter 过滤
过滤通过一个predicate接口来过滤并只保留符合条件的元素,该操作属于中间操作,所以我们可以在过滤后的结果来应用其他Stream操作(比如forEach)。forEach需要一个函数来对过滤后的元素依次执行。forEach是一个最终操作,所以我们不能在forEach之后来执行其他Stream操作。
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) {
List<String> stringCollection = new ArrayList<>();
stringCollection.add("ddd2");
stringCollection.add("aaa2");
stringCollection.add("bbb1");
stringCollection.add("aaa1");
stringCollection.add("bbb3");
stringCollection.add("ccc");
stringCollection.add("bbb2");
stringCollection.add("ddd1");
stringCollection
.stream()
.filter((s) -> s.startsWith("a"))
.forEach(System.out::println); // "aaa2", "aaa1"
System.out.println("stringCollection :" + stringCollection);
}
八、Sort 排序
排序是一个中间操作,返回的是排序好后的Stream。如果你不指定一个自定义的Comparator则会使用默认排序。
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) {
List<String> stringCollection = new ArrayList<>();
stringCollection.add("ddd2");
stringCollection.add("aaa2");
stringCollection.add("bbb1");
stringCollection.add("aaa1");
stringCollection.add("bbb3");
stringCollection.add("ccc");
stringCollection.add("bbb2");
stringCollection.add("ddd1");
stringCollection
.stream()
.sorted()
.filter((s) -> s.startsWith("a"))
.forEach(System.out::println);// "aaa1", "aaa2"
//需要注意的是,排序只创建了一个排列好后的Stream,而不会影响原有的数据源,排序之后原数据stringCollection是不会被修改的。
System.out.println("stringCollection :" + stringCollection); //[ddd2, aaa2, bbb1, aaa1, bbb3, ccc, bbb2, ddd1]
}
}
九、Map 映射
中间操作map会将元素根据指定的Function接口来依次将元素转成另外的对象,下面的示例展示了将字符串转换为大写字符串。你也可以通过map来讲对象转换成其他类型,map返回的Stream类型是根据你map传递进去的函数的返回值决定的。
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) {
List<String> stringCollection = new ArrayList<>();
stringCollection.add("ddd2");
stringCollection.add("aaa2");
stringCollection.add("bbb1");
stringCollection.add("aaa1");
stringCollection.add("bbb3");
stringCollection.add("ccc");
stringCollection.add("bbb2");
stringCollection.add("ddd1");
stringCollection
.stream()
.map(String::toUpperCase)
.sorted((a, b) -> b.compareTo(a))
.forEach(System.out::println); //"DDD2", "DDD1", "CCC", "BBB3", "BBB2", "AAA2", "AAA1"
System.out.println("stringCollection :" + stringCollection); //[ddd2, aaa2, bbb1, aaa1, bbb3, ccc, bbb2, ddd1]
}
}
十、Match 匹配
Stream提供了多种匹配操作,允许检测指定的Predicate是否匹配整个Stream。所有的匹配操作都是最终操作,并返回一个boolean类型的值。
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) {
List<String> stringCollection = new ArrayList<>();
stringCollection.add("ddd2");
stringCollection.add("aaa2");
stringCollection.add("bbb1");
stringCollection.add("aaa1");
stringCollection.add("bbb3");
stringCollection.add("ccc");
stringCollection.add("bbb2");
stringCollection.add("ddd1");
boolean anyStartsWithA =
stringCollection
.stream()
.anyMatch((s) -> s.startsWith("a"));
System.out.println(anyStartsWithA); // true
boolean allStartsWithA =
stringCollection
.stream()
.allMatch((s) -> s.startsWith("a"));
System.out.println(allStartsWithA); // false
boolean noneStartsWithZ =
stringCollection
.stream()
.noneMatch((s) -> s.startsWith("z"));
System.out.println(noneStartsWithZ); // true
System.out.println("stringCollection :" + stringCollection); //[ddd2, aaa2, bbb1, aaa1, bbb3, ccc, bbb2, ddd1]
}
十一、Count 计数
计数是一个最终操作,返回Stream中元素的个数,返回值类型是long。
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) {
List<String> stringCollection = new ArrayList<>();
stringCollection.add("ddd2");
stringCollection.add("aaa2");
stringCollection.add("bbb1");
stringCollection.add("aaa1");
stringCollection.add("bbb3");
stringCollection.add("ccc");
stringCollection.add("bbb2");
stringCollection.add("ddd1");
long startsWithB =
stringCollection
.stream()
.filter((s) -> s.startsWith("b"))
.count();
System.out.println(startsWithB); // 3
System.out.println("stringCollection :" + stringCollection); // [ddd2, aaa2, bbb1, aaa1, bbb3, ccc, bbb2, ddd1]
}
}
十二、Reduce 规约
这是一个最终操作,允许通过指定的函数来讲stream中的多个元素规约为一个元素,规越后的结果是通过Optional接口表示的:
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
public class Test {
public static void main(String[] args) {
List<String> stringCollection = new ArrayList<>();
stringCollection.add("ddd2");
stringCollection.add("aaa2");
stringCollection.add("bbb1");
stringCollection.add("aaa1");
stringCollection.add("bbb3");
stringCollection.add("ccc");
stringCollection.add("bbb2");
stringCollection.add("ddd1");
Optional<String> reduced =
stringCollection
.stream()
.sorted()
.reduce((s1, s2) -> s1 + "#" + s2);
reduced.ifPresent(System.out::println); //aaa1#aaa2#bbb1#bbb2#bbb3#ccc#ddd1#ddd2
System.out.println("stringCollection :" + stringCollection); // [ddd2, aaa2, bbb1, aaa1, bbb3, ccc, bbb2, ddd1]
}
}
十三、并行Streams
前面提到过Stream有串行和并行两种,串行Stream上的操作是在一个线程中依次完成,而并行Stream则是在多个线程上同时执行。
计算串行排序耗时多久
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
public class Test {
public static void main(String[] args) {
int max = 1000000;
List<String> values = new ArrayList<>(max);
for (int i = 0; i < max; i++) {
UUID uuid = UUID.randomUUID();
values.add(uuid.toString());
}
long t0 = System.nanoTime();
long count = values.stream().sorted().count();
System.out.println(count);
long t1 = System.nanoTime();
long millis = TimeUnit.NANOSECONDS.toMillis(t1 - t0);
System.out.println(String.format("sequential sort took: %d ms", millis));
// sequential sort took: 658 ms执行几次,大概就是六百多毫秒
}
}
计算串行排序耗时多久
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
public class Test {
public static void main(String[] args) {
int max = 1000000;
List<String> values = new ArrayList<>(max);
for (int i = 0; i < max; i++) {
UUID uuid = UUID.randomUUID();
values.add(uuid.toString());
}
long t0 = System.nanoTime();
long count = values.parallelStream().sorted().count();
System.out.println(count);
long t1 = System.nanoTime();
long millis = TimeUnit.NANOSECONDS.toMillis(t1 - t0);
System.out.println(String.format("parallel sort took: %d ms", millis));
// parallel sort took: 379 ms 执行几次,大概就是三百多毫秒
}
}
唯一需要做的改动就是将stream()改为parallelStream(),速度直接快一倍
本文作者:魂皓轩 欢迎关注公众号
本人保留所有权益,转载请注明出处。
欢迎有故事、有想法的朋友和我分享,可发送至 e-mail: lwqforit@163.com
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。