如何使用 Stream API 通过 getId() 从 Category 对象本身获取密钥,将其放入 Map<Integer, Category>List 的所有值<Category>?

问题描述 投票:0回答:1

我使用循环遍历类别列表,对于每个类别对象,使用 getId() 方法获取其 id 并将其用作将类别对象放入映射中的键。这是一个示例代码片段:

Map<Integer, Category> categoryMap = new HashMap<>();
List<Category> categoryList = // get the list of categories from somewhere

for (Category category : categoryList) {
    int categoryId = category.getId();
    categoryMap.put(categoryId, category);
}

此代码创建一个名为categoryMap的新HashMap,然后使用for-each循环迭代categoryList。对于列表中的每个类别对象,它使用 getId() 获取 id,然后使用 id 作为键将类别对象放入映射中。

此循环完成后,categoryMap 将包含categoryList 中的所有类别,并以它们的 id 为键。

但是如何将其与 Stream API 一起使用呢?如果我想连接 2 个列表?

java collections java-stream
1个回答
0
投票

我使用

Collectors.toMap()
方法将两个列表中的元素收集到单个映射中,其中键取自每个
getId()
对象的
Category
方法。这是一个示例代码片段:

List<Category> categoryList1 = // get the first list of categories from somewhere
List<Category> categoryList2 = // get the second list of categories from somewhere

Map<Integer, Category> categoryMap = Stream.concat(categoryList1.stream(), categoryList2.stream())
    .collect(Collectors.toMap(Category::getId, Function.identity()));

此代码使用

Stream.concat()
连接两个列表,然后使用
Collectors.toMap()
将两个列表中的元素收集到单个映射中。
toMap()
的第一个参数是从每个
Category
对象中提取密钥的函数(在本例中为
Category::getId
),第二个参数是返回相应
Category
对象的函数(在本例中为
Function.identity()
)。

执行此代码后,

categoryMap
将包含两个列表中的所有类别,并以它们的 id 作为键。如果有重复的 id,将会抛出异常。要处理重复项,您可以提供合并函数作为
toMap()
的第三个参数。

© www.soinside.com 2019 - 2024. All rights reserved.