写在前面
Java 8中的集合框架
接口名
|
Java8新加入的方法
|
Collection
|
forEach(), removeIf(), stream(), parallelStream()
|
List
|
replaceAll(), sort()
|
Map
|
forEach(), replaceAll(), compute(), computeIfAbsent(), computeIfPresent(), merge()
|
一个函数,如果它有一个或多个参数是函数类型的,或者它的返回值是函数类型的,那么我们称这个函数为高阶函数。
public class Container implements Collection { ... }
升级到Java 8后,因为Collection中新增了方法 forEach,假设没有默认方法,之前的类 Container 将编译失败。
Collection中的高阶函数
1. forEach
default void forEach(Consumer<? super T> action) {
Objects.requireNonNull(action);
for (T t : this) {
action.accept(t);
}
}
它的作用是遍历集合中的每一个元素,然后依次对每个元素执行参数 action 指定的动作。参数 action 是一个 Consumer 类型的函数式接口,我们可以通过lambda表达式或方法引用来实现一个 Consumer 。因此,在Java 8或以后的版本中,不要用 for 语句来迭代 Collection 了,不妨使用 forEach 方法。
示例代码如下:
public static void collectionForEach() {
Collection<String> list = Arrays.asList("Guangdong", "Zhejiang", "Jiangsu"); // for 语句
for (String s : list) {
System.out.println(s);
} // forEach 方法 + lambda表达式
list.forEach(s -> System.out.println(s)); // forEach 方法 + 方法引用
list.forEach(System.out::println);
}
2. removeIf
default boolean removeIf(Predicate<? super E> filter) { ... }
removeIf的作用是遍历集合中的每一个元素,然后依次对每个元素进行指定的过滤操作。filter 参数是一个 Predicate 类型的函数式接口。
示例代码如下,假定我们要过滤掉以字母 G 开头的省份:
public static void collectionRemoveIf() {
List<String> provinces = new ArrayList<>(Arrays.asList("Guangdong", "Jiangsu", "Guangxi", "Jiangxi", "Shandong")); boolean removed = provinces.removeIf(s -> {
return s.startsWith("G");
}); System.out.println(removed);
System.out.println(provinces);
}
上述代码输出为:
3. replaceAll
default void replaceAll(UnaryOperator<E> operator) { ... }
replaceAll方法的作用是对集合中的每个元素执行 operator 指定的计算,并用计算结果替换原来的元素。参数 operator 是类型为 UnaryOperator 的函数式接口,它的参数和返回值类型是相同的。
public static void listReplaceAll() {
List<String> provinces = Arrays.asList("Guangdong", "Jiangsu", "Guangxi", "Jiangxi", "Shandong");
provinces.replaceAll(s -> s.toUpperCase());
System.out.println(provinces);
}
上述代码的输出为:
4. sort
default void sort(Comparator<? super E> c) { ... }
sort方法是根据比较器 c 指定的排序规则,对 List 中的元素进行排序。参数 c 的类型是Comparator,同样是一个函数式接口。
public static void listSort() {
List<String> list = Arrays.asList("Guangdong", "Zhejiang", "Jiangsu", "Xizang", "Fujian", "Hunan", "Guangxi"); // 对省份进行排序,首先按照长度排序,如果长度一样,则按照字母顺序排序
list.sort((first, second) -> {
int lenDiff = first.length() - second.length();
return lenDiff == 0 ? first.compareTo(second) : lenDiff;
}); list.forEach(s -> System.out.println(s));
}
上述代码的输出为:
5. stream 和 parallelStream
Map中的高阶函数
1. forEach
default void forEach(BiConsumer<? super K, ? super V> action) { ... }
可以看到,Map的forEach方法的作用是遍历Map中所有的键值对,并执行参数 action 指定的操作。参数 action 的类型是函数式接口 BiConsumer,要求有2个参数,分别代表键值对的key和value。
public static void mapForEach() {
Map<String, String> cityMap = new HashMap<>();
cityMap.put("Guangdong", "Guangzhou");
cityMap.put("Zhejiang", "Hangzhou");
cityMap.put("Jiangsu", "Nanjing"); cityMap.forEach((key, value) -> {
System.out.println(String.format("%s 的省会是 %s", key, value));
});
}
上述代码的输出为:
2. replaceAll
default void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) { ... }
public static void mapReplaceAll() {
Map<String, String> cityMap = new HashMap<>();
cityMap.put("Guangdong", "Guangzhou");
cityMap.put("Zhejiang", "Hangzhou");
cityMap.put("Jiangsu", "Nanjing"); // 将省府的拼音转换为大写
cityMap.replaceAll((key, value) -> {
return value.toUpperCase();
}); cityMap.forEach((key, value) -> {
System.out.println(String.format("%s 的省会大写是 %s", key, value));
});
}
3. compute
default V compute(K key,
BiFunction<? super K, ? super V, ? extends V> remappingFunction) { ... }
示例代码如下:
public static void mapCompute() {
Map<String, String> cityMap = new HashMap<>();
cityMap.put("Guangdong", "null");
cityMap.put("Zhejiang", "Hangzhou");
cityMap.put("Jiangsu", "null"); // 稍显复杂的语句,先调用 forEach 遍历 cityMap 中的键,然后根据原有的键值对计算新的值
Set keys = new HashSet<>(cityMap.keySet());
keys.forEach(key -> {
cityMap.compute(key, (k, v) -> {
// 如果是 Guangdong,则返回 Guangzhou
if ("Guangdong".equals(k)) {
return "Guangzhou";
} // 如果旧的键值对中,值是字符串 "null" ,则返回 null。
// 这意味着 cityMap 会删除对应的key
if ("null".equals(v)) {
return null;
} // 否则,返回原来的 value 值
return v;
});
}); cityMap.forEach((key, value) -> {
System.out.println(String.format("%s 的省会是 %s", key, value));
});
}
上述代码的输出为:
4. computeIfPresent
default V computeIfPresent(K key,
BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
Objects.requireNonNull(remappingFunction);
V oldValue;
if ((oldValue = get(key)) != null) {
V newValue = remappingFunction.apply(key, oldValue);
if (newValue != null) {
put(key, newValue);
return newValue;
} else {
remove(key);
return null;
}
} else {
return null;
}
}
5. computeIfAbsent
default V computeIfAbsent(K key,
Function<? super K, ? extends V> mappingFunction) {
Objects.requireNonNull(mappingFunction);
V v;
if ((v = get(key)) == null) {
V newValue;
if ((newValue = mappingFunction.apply(key)) != null) {
put(key, newValue);
return newValue;
}
} return v;
}
public static void mapComputeIfAbsent() {
Map<String, Integer> staffMap = new HashMap<>();
staffMap.put("Lilei", 24);
staffMap.put("Hanmeimei", 22);
staffMap.put("Liming", 24);
staffMap.put("Jim", 22);
staffMap.put("David", 24); Map<Integer, List<String>> staffInvertMap = new HashMap<>();
staffMap.forEach((key, value) -> {
// 以年龄为键,构建一个新的Map
// 以 22 岁为例:
// 如果 staffInvertMap 之前不存在 22 岁对应的映射关系,
// 则新建一个 "年龄 -> ArrayList<String>" 的映射,并且把新建的 ArrayList 返回。
// 如果 staffInvertMap 已经存在 22 岁对应的映射关系了,则将已存在的 ArrayList 返回。
List<String> nameList = staffInvertMap.computeIfAbsent(value, age -> {
// 对于同一个 age,这句代码只会执行一次
return new ArrayList<>();
}); nameList.add(key);
}); System.out.println(staffInvertMap);
}
6. merge
default V merge(K key, V value,
BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
Objects.requireNonNull(remappingFunction);
Objects.requireNonNull(value);
V oldValue = get(key);
V newValue = (oldValue == null) ? value :
remappingFunction.apply(oldValue, value);
if(newValue == null) {
remove(key);
} else {
put(key, newValue);
}
return newValue;
}
public static void mapMerge() {
Map<String, String> staffMap = new HashMap<>();
staffMap.put("Lilei", "性别男 "); // 等价于 staffMap.merge("Lilei", "年龄 24", String::concat)
// oldValue 即之前添加的值 “性别男 ”,value 即merge函数的第二个参数 “年龄24”
staffMap.merge("Lilei", " 年龄24", (oldValue, value) -> oldValue.concat(value));
staffMap.merge("Hanmeimei", "年龄22", String::concat); System.out.println(staffMap);
}