首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >循环遍历对象列表,并使用Java 8构建一个Map

循环遍历对象列表,并使用Java 8构建一个Map
EN

Stack Overflow用户
提问于 2022-08-26 19:05:14
回答 2查看 114关注 0票数 0

我有ElementCharacteristic的名单。我想循环遍历这个列表并构建一个Map。如何在中做到这一点?

代码语言:javascript
复制
public Map<String,String> getMap(List<ElementCharacteristic> inputList) {
    Map<String,String> outPutMap = new HashMap<>();
    for(ElementCharacteristic ele : inputList) {
        outPutMap.put(ele.getCharacteristic(),ele.getFeature());
    }
    return outPutMap;
}
EN

回答 2

Stack Overflow用户

发布于 2022-08-26 19:21:14

您可能可以使用以下代码:

代码语言:javascript
复制
Map<String, String> outPutMap = new HashMap<>();
inputList.stream()
    .map(p->outPutMap.put(p.getCharacteristic(), p.getFeature()));

或者这个:

代码语言:javascript
复制
Map<String,String> outPutMap = inputList .stream()
.collect(Collectors.toMap(p-> p.getCharacteristic(), p-> p.getFeature()));
票数 0
EN

Stack Overflow用户

发布于 2022-08-27 18:10:09

您可以使用Collectors.toMap函数来实现这一点:

代码语言:javascript
复制
public Map<String,String> getMap(List<ElementCharacteristic> inputList) {
    return inputList.stream()
            .collect(Collectors.toMap(ElementCharacteristic::getCharacteristic, ElementCharacteristic::getFeature));
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73505510

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档