如何在HashMap中为同一个键存储多个值?

时间:2016-11-08 09:15:39

标签: java hashmap

我有一个名为InputRow的字符串,如下所示:

1,Kit,23
2,Ret,211

我在其上应用正则表达式(.+),(.+),(.+)并将结果存储在多个变量中。

对于第一行1,kit,23,我得到:

InputRow.1-->1
InputRow.2-->kit
InputRow.3-->23

对于第二行2,Ret,211,我得到:

InputRow.1-->2
InputRow.2-->Ret
InputRow.3-->211

我想将HashMap中的所有输入行与相同的密钥InputRow存储在一起。我怎么能用Java做到这一点?

我的Java代码是..,

line="1,Kit,23";
final Map<String, String> regexResults = new HashMap<>();
Pattern pattern = Pattern.compile("(.+),(.+),(.+)");
final Matcher matcher = pattern.matcher(line);
if (matcher.find()) 
{
final String baseKey = "InputRow";
for (int i = 0; i <= matcher.groupCount(); i++) {
final String key = new StringBuilder(baseKey).append(".").append(i).toString();
 String value = matcher.group(i);
if (value != null) {
   regexResults.put(key, value);
}
}

现在我想将第二行存储在&#34; regexResults&#34;处理。怎么可能?

2 个答案:

答案 0 :(得分:3)

创建课程{"1478596579898":{"http://stackoverflow.com/questions/40410927/phantomjs-from-node-on-windows":["en.wikipedia.org/wiki/File_URI_scheme – Igor 2 days ago\n","@Igor is there something in particular you see wrong, or are you suggesting the phantom module has an incorrect URI? – Danny Buonocore 2 days ago\n","Probably windows security issue not allowing to run an unsigned program. – Vaviloff yesterday\n"],"http://stackoverflow.com/questions/40412726/casperjs-iterating-over-a-list-of-links-using-casper-each":["Thanks, this looked really promising. I made the changes but it didn't solve the problem. And I just realised that in debug mode the following happens: Creating new array object for https://example.com [debug] [phantom] Navigation requested: url=about:blank, type=Other, willNavigate=true, isMainFrame=true and then Casperjs silently fails. It seems that the correct link that gets passed into thenOpen gets changed to about:blank... – cyc665 yesterday\n"]}}

InputRow

class InputRow { private int value1; private String value2; private int value3; //...getters and setters } 。哈希映射键是您的行索引,您将所有匹配的行分配为哈希映射的HashMap<Integer, List<InputRow>>

为了澄清,List<InputRow>存储一个唯一键的一个条目。因此,您不能将多个条目分配给同一个键,否则该条目将被覆盖。因此,您需要编写一个容器来覆盖多个对象或使用现有的HashMap

您的代码示例

我使用了两个文本片段,用换行符分隔,因此有两行。此代码段将列表中的两个List对象放入InputRow,其键为“InputRow”。请注意,匹配器组索引从HashMap开始,零表示整个组。还要注意,为简单起见,我假设您创建了一个1构造函数。

InputRow(String, String, String)

答案 1 :(得分:1)

这是不可能的。 Map每个定义只能存储一个密钥。文档说

  

将键映射到值的对象。地图不能包含重复的键;每个键最多可以映射一个值。

您唯一能做的就是将键映射到值列表。 Map<String, List<String>>。然后它看起来像这样

InputRow.1 --> [1, kit, 23],
InputRow.2 --> [2, Ret, 211]
相关问题