1、内置的函数式接口
JDK 1.8 API 包含了很多内置的函数式接口。其中就包括我们在老版本中经常见到的 Comparator 和 Runnable,Java 8 为他们都添加了 @FunctionalInterface 注解,以用来支持 Lambda 表达式。
值得一提的是,除了 Comparator 和 Runnable 外,还有一些新的函数式接口,它们很多都借鉴于知名的 Google Guava 库。
(1). Predicate 断言
Predicate 是一个可以指定入参类型,并返回 boolean 值的函数式接口。它内部提供了一些带有默认实现的方法,可以被用来组合一个复杂的逻辑判断( and, or,negate)
Predicate<String> predicate = (s) -> s.length() > 0;
predicate.test("foo"); // true
predicate.negate().test("foo"); // false
Predicate<Boolean> nonNull = Objects::nonNull;
Predicate<Boolean> isNull = Objects::isNull;
Predicate<String> isEmpty = String::isEmpty;
Predicate<String> isNotEmpty = isEmpty.negate();
(2). Function
Function 函数式接口的作用是,我们可以为其提供一个原料,他给生产一个最终的产品。通过它提供的默认方法,组合,链行处理( compose, andThen):
Function<String, Integer> toInteger = Integer::valueOf;
Function<String, String> backToString = toInteger.andThen(String::valueOf);
backToString.apply("123"); // "123"
(3). Supplier 生产者
Supplier 与 Function 不同,它不接受入参,直接为我们生产一个指定的结果,有点像生产者模式:
class Person {
String firstName;
String lastName;
Person() {}
Person(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
}
Supplier<Person> personSupplier = Person::new;
personSupplier.get(); // new Person
(4). Consumer 消费者
对于 Consumer,我们需要提供入参,用来被消费,如下面这段示例代码:
class Person {
String firstName;
String lastName;
Person() {}
Person(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
}
Consumer<Person> greeter = (p) -> System.out.println("Hello, " + p.firstName);
greeter.accept(new Person("Luke", "Skywalker"));
(5). Comparator
Comparator 在 Java 8 之前是使用比较普遍的。Java 8 中除了将其升级成了函数式接口,还为它拓展了一些默认方法:
Comparator<Person> comparator = (p1, p2) -> p1.firstName.compareTo(p2.firstName);
Person p1 = new Person("John", "Doe");
Person p2 = new Person("Alice", "Wonderland");
comparator.compare(p1, p2); // > 0
comparator.reversed().compare(p1, p2); // < 0
(6). Optional
首先, Optional 它不是一个函数式接口,设计它的目的是为了防止空指针异常( NullPointerException),要知道在 Java 编程中,空指针异常可是臭名昭著的。
让我们来快速了解一下 Optional 要如何使用!你可以将 Optional 看做是包装对象(可能是 null, 也有可能非 null)的容器。当你定义了一个方法,这个方法返回的对象可能是空,也有可能非空的时候,你就可以考虑用 Optional 来包装它,这也是在 Java 8 被推荐使用的做法。
Optional<String> optional = Optional.of("bam");
optional.isPresent(); // true
optional.get(); // "bam"
optional.orElse("fallback"); // "bam"
optional.ifPresent((s) -> System.out.println(s.charAt(0))); // "b"
2、Map 集合
前面已经提到过 Map 是不支持 Stream 流的,因为 Map 接口并没有像 Collection 接口那样,定义了 stream() 方法。但是,我们可以对其 key, values, entry 使用流操作,如 map.keySet().stream(), map.values().stream() 和 map.entrySet().stream().
另外, JDK 8 中对 map 提供了一些其他新特性:
Map<Integer, String> map = new HashMap<>();
for (int i = 0; i < 10; i++) {
// 与老版不同的是,putIfAbent() 方法在 put 之前,会判断 key 是否已经存在,
//存在则直接返回 value, 否则 put, 再返回 value
map.putIfAbsent(i, "val" + i);
}
// forEach 可以很方便地对 map 进行遍历操作
map.forEach((key, value) -> System.out.println(value));
除了上面的 putIfAbsent() 和 forEach() 外,还可以很方便地对某个 key 的值做相关操作:
// computeIfPresent(), 当 key 存在时,才会做相关处理 如下:对 key 为 3 的值,
//内部会先判断值是否存在,存在,则做 value + key 的拼接操作
map.computeIfPresent(3, (num, val) -> val + num);
map.get(3); // val33
// 先判断 key 为 9 的元素是否存在,存在,则做删除操作
map.computeIfPresent(9, (num, val) -> null);
map.containsKey(9); // false
// computeIfAbsent(), 当 key 不存在时,才会做相关处理 如下:先判断 key 为 23 的元素是否存在,
//不存在,则添加
map.computeIfAbsent(23, num -> "val" + num);
map.containsKey(23); // true
// 先判断 key 为 3 的元素是否存在,存在,则不做任何处理
map.computeIfAbsent(3, num -> "bam");
map.get(3); // val33
关于删除操作,JDK 8 中提供了能够新的 remove() API:
map.remove(3, "val3");
map.get(3); // val33
map.remove(3, "val33");
map.get(3); // null
如上代码,只有当给定的 key 和 value 完全匹配时,才会执行删除操作。
关于添加方法,JDK 8 中提供了带有默认值的 getOrDefault() 方法:
// 若 key 42 不存在,则返回 not found
map.getOrDefault(42, "not found"); // not found
对于 value 的合并操作也变得更加简单:
// merge 方法,会先判断进行合并的 key 是否存在,不存在,则会添加元素
map.merge(9, "val9", (value, newValue) -> value.concat(newValue));
map.get(9); // val9
// 若 key 的元素存在,则对 value 执行拼接操作
map.merge(9, "concat", (value, newValue) -> value.concat(newValue));
map.get(9); // val9concat
作者:xxx
链接:xxx
来源:xxx
3、Map 操作之 merge()
3.1、merge()用法
有一个学生成绩对象的列表,对象包含学生姓名、科目、科目分数三个属性,要求求得每个学生的总成绩。加入列表如下:
private List<StudentScore> buildATestList() {
List<StudentScore> studentScoreList = new ArrayList<>();
StudentScore studentScore1 = new StudentScore() {{
setStuName("张三");
setSubject("语文");
setScore(70);
}};
StudentScore studentScore2 = new StudentScore() {{
setStuName("张三");
setSubject("数学");
setScore(80);
}};
StudentScore studentScore3 = new StudentScore() {{
setStuName("张三");
setSubject("英语");
setScore(65);
}};
StudentScore studentScore4 = new StudentScore() {{
setStuName("李四");
setSubject("语文");
setScore(68);
}};
StudentScore studentScore5 = new StudentScore() {{
setStuName("李四");
setSubject("数学");
setScore(70);
}};
StudentScore studentScore6 = new StudentScore() {{
setStuName("李四");
setSubject("英语");
setScore(90);
}};
StudentScore studentScore7 = new StudentScore() {{
setStuName("王五");
setSubject("语文");
setScore(80);
}};
StudentScore studentScore8 = new StudentScore() {{
setStuName("王五");
setSubject("数学");
setScore(85);
}};
StudentScore studentScore9 = new StudentScore() {{
setStuName("王五");
setSubject("英语");
setScore(70);
}};
studentScoreList.add(studentScore1);
studentScoreList.add(studentScore2);
studentScoreList.add(studentScore3);
studentScoreList.add(studentScore4);
studentScoreList.add(studentScore5);
studentScoreList.add(studentScore6);
studentScoreList.add(studentScore7);
studentScoreList.add(studentScore8);
studentScoreList.add(studentScore9);
return studentScoreList;
}
===================常规做法===================
ObjectMapper objectMapper = new ObjectMapper();
List<StudentScore> studentScoreList = buildATestList();
Map<String, Integer> studentScoreMap = new HashMap<>();
studentScoreList.forEach(studentScore -> {
if (studentScoreMap.containsKey(studentScore.getStuName())) {
studentScoreMap.put(studentScore.getStuName(),
studentScoreMap.get(studentScore.getStuName()) + studentScore.getScore());
} else {
studentScoreMap.put(studentScore.getStuName(), studentScore.getScore());
}
});
System.out.println(objectMapper.writeValueAsString(studentScoreMap));
// 结果如下:{"李四":228,"张三":215,"王五":235}
===================merge()做法===================
Map<String, Integer> studentScoreMap2 = new HashMap<>();
studentScoreList.forEach(studentScore -> studentScoreMap2.merge(
studentScore.getStuName(),
studentScore.getScore(),
Integer::sum));
System.out.println(objectMapper.writeValueAsString(studentScoreMap2));
// 结果如下:{"李四":228,"张三":215,"王五":235}
3.2、merge()简介
merge() 可以这么理解:它将新的值赋值到 key (如果不存在)或更新给定的key 值对应的 value,其源码如下:
default V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction)
{
Objects.requireNonNull(remappingFunction);
Objects.requireNonNull(value);
V oldValue = this.get(key);
V newValue = oldValue == null ? value : remappingFunction.apply(oldValue, value);
if (newValue == null) {
this.remove(key);
} else {
this.put(key, newValue);
}
return newValue;
}
我们可以看到原理也是很简单的,该方法接收三个参数,
一个 key 值,一个 value,一个 remappingFunction ,
如果给定的key不存在,它就变成了 put(key, value) 。
如果 key 已经存在一些值,我们 remappingFunction 可以选择合并的方式,
然后将合并得到的 newValue 赋值给原先的 key。
3.2、使用场景
这个使用场景相对来说还是比较多的,比如分组求和这类的操作,虽然 stream 中有相关 groupingBy() 方法,但如果你想在循环中做一些其他操作的时候,merge() 还是一个挺不错的选择的。
3.3、其他
除了 merge() 方法之外,我还看到了一些Java 8 中 map 相关的其他方法,比如 putIfAbsent 、compute() 、computeIfAbsent() 、computeIfPresent,这些方法我们看名字应该就知道是什么意思了,故此处就不做过多介绍了,感兴趣的可以简单阅读一下源码(都还是挺易懂的),这里我们贴一下 compute()(Map.class) 的源码,其返回值是计算后得到的新值:
default V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
Objects.requireNonNull(remappingFunction);
V oldValue = this.get(key);
V newValue = remappingFunction.apply(key, oldValue);
if (newValue == null) {
if (oldValue == null && !this.containsKey(key)) {
return null;
} else {
this.remove(key);
return null;
}
} else {
this.put(key, newValue);
return newValue;
}
}
3.4、总结
本文简单介绍了一下 Map.merge() 的方法,除此之外,Java 8 中的 HashMap 实现方法使用了 TreeNode 和 红黑树,在源码阅读上可能有一点难度,不过原理上还是相似的,compute() 同理。所以,源码肯定是要看的,不懂的地方多读多练自然就理解了。
参考:https://www.jianshu.com/p/68e6b30410b0
代码地址:https://github.com/lq920320/algorithm-java-test/blob/master/src/test/java/other/MapMethodsTest.java
作者:LQ木头
链接:juejin.im/post/5d9b455ae51d45782b0c1bfb
来源:掘金