Swift编程轻松掌握Java Stream流List< T >转换Map方法汇总合集
2023-05-30 09:54:23
轻松驾驭 Java Stream:将 List 转换为 Map 的方法大全
在 Java 中处理数据时,将 List 转换成 Map 是一种常见的需求。Stream API 提供了多种实用方法来实现这一转换,本文将深入探讨这些方法,让您在数据操作中如鱼得水。
一、toMap() 方法:直接转换法
toMap() 方法是一种直接将 List 转换为 Map 的便捷方法。它的工作原理如下:
Map<K, V> map = list.stream().collect(Collectors.toMap(k -> k.getKey(), v -> v.getValue()));
其中,k
和 v
分别是 List 中元素的键和值。toMap() 方法将每个元素的键值对作为 Map 的键值对,从而生成一个新的 Map。
二、groupingBy() 方法:分组转换法
groupingBy() 方法可以根据元素的属性将 List 进行分组,并返回一个 Map,其中键是分组属性值,值是属于该组的元素列表。用法如下:
Map<K, List<V>> map = list.stream().collect(Collectors.groupingBy(k -> k.getKey()));
其中,k
是 List 中元素的属性。groupingBy() 方法将元素按属性值分组,返回一个 Map,其中键是属性值,值是属于该分组的元素列表。
三、partitioningBy() 方法:条件划分法
partitioningBy() 方法可以根据元素是否满足某个条件将 List 分为两组,并返回一个 Map,其中键是 true 和 false,值是满足和不满足条件的元素列表。用法如下:
Map<Boolean, List<V>> map = list.stream().collect(Collectors.partitioningBy(v -> v.getValue() > 10));
其中,v
是 List 中元素的属性。partitioningBy() 方法将元素按条件分组,返回一个 Map,其中键是 true 和 false,值是满足和不满足条件的元素列表。
代码示例
为了更好地理解这些方法,让我们通过一个示例来演示:
List<Student> students = List.of(
new Student("John", "Doe", 22),
new Student("Jane", "Smith", 25),
new Student("Peter", "Parker", 21),
new Student("Mary", "Johnson", 23)
);
// 使用 toMap() 方法根据姓名创建 Map
Map<String, Student> studentMap = students.stream()
.collect(Collectors.toMap(Student::getName, student -> student));
// 使用 groupingBy() 方法根据年龄分组创建 Map
Map<Integer, List<Student>> studentAgeMap = students.stream()
.collect(Collectors.groupingBy(Student::getAge));
// 使用 partitioningBy() 方法根据是否已成年划分创建 Map
Map<Boolean, List<Student>> adultStudentMap = students.stream()
.collect(Collectors.partitioningBy(student -> student.getAge() >= 18));
总结
利用 Java Stream 的这些强大方法,您可以轻松地将 List 转换为 Map,从而满足您的数据处理需求。无论您需要直接转换、分组还是根据条件划分,都有一个方法可以满足您的需要。
常见问题解答
-
如何将 List 中的对象转换为键值对?
- 使用 toMap() 方法,并指定键和值提取函数。
-
如何根据多个属性对 List 进行分组?
- 使用 Collectors.groupingBy(Function<T, K1>, Collector<T, ?, Map<K2, List
>>),其中 K1 和 K2 是分组属性类型。
- 使用 Collectors.groupingBy(Function<T, K1>, Collector<T, ?, Map<K2, List
-
如何将 List 中的对象按条件分为多个 Map?
- 使用 Collectors.partitioningBy(Predicate
) 方法,其中 Predicate 是测试条件的函数。
- 使用 Collectors.partitioningBy(Predicate
-
如何获取 Map 的键列表?
- 使用 Map.keySet() 方法。
-
如何获取 Map 的值列表?
- 使用 Map.values() 方法。