使用预定义值填充hashmap(java) [英] Populating a hashmap with predefined values (java)

查看:144
本文介绍了使用预定义值填充hashmap(java)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个我以前没有处理过的问题。我正在为java中的数据库写一个补丁,基本上是转换某些行中存储的数据。为了做到这一点,我有一个转换表,告诉我什么值成了什么。



例如,如果我读了RC,AC,GH - >将值更新为T1。 (这些只是随机的例子,它基本上是将一个字符串转换为另一个字符串。)



我需要一种存储这些转换的好方法。我正在考虑一个hashmap:
KEY,VALUE:(RC,T1)(AC,T1)(GH,T1)等等。

现在,有几十个这样的。修补程序初始化时填充此散列映射的干净方式是什么?

解决方案

我将在设置HashMap的同时进行初始化



例如

  private static final Map< String,String> m = new HashMap< String,String>(){{
put(RC,T1);
put(AC,T1);
}};

然后你就可以确保代码中的所有内容一起设置。



我认为@Nambari是一个很好的观点,尽管可能有值作为列表而不仅仅是一个字符串。然而,这会交换您的密钥和值。



eg

  private static final Map< String,List< String>> m = new HashMap< String,List< String>>(){{
put(T1,Arrays.asList(RC,AC);
}};


I've run into a problem I haven't had to deal with before. I'm writing a patch for a database in java that's basically converting data stored in certain rows. In order to do this I have a conversion table that tells me what values become what.

Example, if I read in either "RC", "AC", "GH" -> Update the value to "T1". (These are just random examples, it's basically converting one string to another.)

I need a good way of storing these conversions. I was thinking a hashmap: KEY,VALUE: (RC,T1) (AC,T1) (GH,T1) and so on and so on.

Now, there's dozens and dozens of these. What's a good clean way of populating this hashmap when the patch initializes?

解决方案

I would do the initialisation while setting up the HashMap

For example

private static final Map<String, String> m = new HashMap<String, String>() {{
    put("RC", "T1");
    put("AC", "T1");
}};

Then you wuld make sure that everything is set up together in your code.

I think @Nambari makes a good point though with perhaps having the value as a list rather than just a string. This does then swap your keys and values though.

eg

 private static final Map<String, List<String>> m = new HashMap<String, List<String>>() {{
    put("T1", Arrays.asList("RC", "AC");
}};

这篇关于使用预定义值填充hashmap(java)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆