程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长


+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

暂无数据

从 csv 加载并存储在 HashMap 中,键包含多个值

发布于2022-05-30 07:29     阅读(1265)     评论(0)     点赞(22)     收藏(5)


我有一个哈希图,它存储来自 csv 文件的值。该文件由三列组成:TEMPLATE_NAME、PARAM_1、PARAM_2

我一直在尝试使用 TEMPLATE_NAME 作为键,使用 PARM_1、PARAM_2 作为每一行的值。问题是可能有许多 TEMPLATE_NAME 具有不同的参数组合。我的要求指定选择param_1和param_2时应显示template_name的列表。

我知道哈希图不能有重复的键,所以哈希图只创建一个带有值的 TEMPLATE_NAME 键,但忽略重复项。我该如何解决这个问题?

private void load() throws IOException{
        CsvReader reader = new CsvReader();
        List<List<String>> rows = reader.parse(csvFile);

    for (int i = 1 ; i<rows.size() ; i++){
        List<String> columns = rows.get(i);
        String templateName = columns.get(TEMPLATE_NAME);

        OnConfig config = entries.get(templateName);
        if (config == null){
            config = new OnConfig(templateName);
            entries.put(templateName, config);
        }

        config.put(columns.get(PARAM_1), columns.get(PARAM_2));

    }
}



public class OnConfig {

    private final String templateName;

    private final HashMap<String, String> attributes = new HashMap<>();

    public OnConfig(String templateName){
        this.templateName= templateName;
    }

    public void put(String param1, String param2){
        attributes.put(param1, param2);
    }

    public String get(String param1){
        return attributes.get(param1);
    }

    public String getTemplateName() {
        return templateName;
    }

    @Override
    public String toString() {
        return String.format("Template Name: %s, Number of Attributes: %s", getTemplateName(), attributes.value());
    }
}

解决方案


问题是可能有许多 TEMPLATE_NAME 具有不同的参数组合。

  1. 创建一个表示 TEMPLATE_NAMES 并包含 PARM_1、PARAM_2 的列表或映射的新类

  2. 使用嵌套数据结构。例如,在 Map 中嵌套一个 Map:外键是 TEMPLATE_NAMES,内键是 PARAM_1



所属网站分类: 技术文章 > 问答

作者:黑洞官方问答小能手

链接:http://www.javaheidong.com/blog/article/442917/af9f762d720812bcbda0/

来源:java黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

22 0
收藏该文
已收藏

评论内容:(最多支持255个字符)