collect(Collectors.toMap)和collect(Collectors.Mapping)的区别
在Java 8中,Stream提供了一些操作可以将Stream中的元素收集到集合中,其中collect(Collectors.toMap)和collect(Collectors.mapping)都是收集操作。
collect(Collectors.toMap)是将Stream中的元素收集到一个Map中,其中可以指定key和value的映射关系,也可以指定当出现重复key时的合并方式。
而collect(Collectors.mapping)则是将Stream中的元素转换为另一个集合类型,例如将Stream中的元素转换为List、Set等,同时还可以指定一个转换函数。
区别在于,collect(Collectors.toMap)最终收集的结果是一个Map类型,而collect(Collectors.mapping)最终收集的结果是一个集合类型,例如List、Set等。另外,collect(Collectors.toMap)需要指定key和value的映射关系,而collect(Collectors.mapping)则只需要指定一个转换函数即可。
需要注意的是,collect(Collectors.toMap)中需要考虑key的重复问题,而collect(Collectors.mapping)不需要考虑这个问题。同时,在使用collect(Collectors.mapping)时,还需要注意转换函数的使用,因为转换函数会影响最终收集到的集合类型。
Collectors.toMap换成Collectors.mapping
Collectors.toMap和Collectors.mapping都是Java 8中的流操作工具类Collectors的方法,用于对流中的元素进行收集和转换。
Collectors.toMap方法用于将流中的元素映射为键值对,并将其收集到一个Map中。它接受两个参数,第一个参数是用于提取键的函数,第二个参数是用于提取值的函数。如果流中存在重复的键,则会抛出一个IllegalStateException异常。
而Collectors.mapping方法则是在收集元素到Map时,对元素进行进一步的转换操作。它接受两个参数,第一个参数是用于提取键的函数,第二个参数是用于对值进行转换的函数。它可以与其他收集器一起使用,例如Collectors.toList或Collectors.toSet,来对值进行进一步的收集和转换。
下面是一个示例代码,演示了如何使用Collectors.toMap和Collectors.mapping方法:
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class Example {
public static void main(String[] args) {
List<String> fruits = Arrays.asList("apple", "banana", "orange");
// 使用Collectors.toMap将水果列表转换为以长度为键,水果名称为值的Map
Map<Integer, String> lengthToNameMap = fruits.stream()
.collect(Collectors.toMap(String::length, fruit -> fruit));
System.out.println(lengthToNameMap);
// 使用Collectors.mapping将水果列表转换为以长度为键,水果名称列表为值的Map
Map<Integer, List<String>> lengthToNamesMap = fruits.stream()
.collect(Collectors.groupingBy(String::length, Collectors.mapping(fruit -> fruit, Collectors.toList())));
System.out.println(lengthToNamesMap);
}
}
输出结果为:
{5=apple, 6=orange, 6=banana}
{5=[apple], 6=[orange, banana]}
Map<String, String> stringMap = byTemplateAndExpert.stream().collect(Collectors.toMap(AssessJoinExpertEntity::getSettingId, AssessJoinExpertEntity::getId));
这段代码使用了 Java 8 的 Stream API 对 byTemplateAndExpert 集合中的 AssessJoinExpertEntity 对象进行操作,将每个元素的 settingId 属性作为 key,将 id 属性作为 value,最终生成一个 Map<String, String> 类型的结果。
这段代码的实现方式相对简单,但存在一些潜在问题。首先,如果 byTemplateAndExpert 集合中的元素存在 settingId 属性值相同的情况,那么会抛出 IllegalStateException 异常,提示 key 值冲突。其次,如果 byTemplateAndExpert 集合中的元素的 settingId 或 id 属性值为 null,那么也会抛出 NullPointerException 异常。
为了避免这些问题,可以通过使用 groupingBy 方法对集合元素进行分组,再对每个组内的元素进行操作。具体实现方式可以参考下面的代码:
Map<String, String> stringMap = byTemplateAndExpert.stream()
.collect(Collectors.groupingBy(AssessJoinExpertEntity::getSettingId, Collectors.mapping(AssessJoinExpertEntity::getId, Collectors.joining(","))));
这段代码中,先使用 groupingBy 方法将元素按照 settingId 属性值进行分组,然后使用 mapping 方法将每个组内的元素的 id 属性值转换成字符串,并用逗号进行连接,最后生成一个 Map<String, String> 类型的结果。这种实现方式可以避免 key 值冲突和 NPE 异常。
相关推荐















