【问题标题】:Converting Hashmap into single string array in java在java中将Hashmap转换为单个字符串数组
【发布时间】:2016-12-20 09:06:54
【问题描述】:

我正在编写一个课程计划,并且已经为此绞尽脑汁好几天了。我必须找到字符串中出现的次数。我已经能够将结果放入 HashMap 中。但是,我需要能够将其转换为单个字符串数组,以便我可以 assertTrue 并对其进行测试。这是我到目前为止所拥有的。任何建议将不胜感激。谢谢。

public static void main(String[] args) 
    {
        String input = "xyz 456 123 123 123 123 123 123 xy 98 98 xy xyz abc abc 456 456 456  98 xy"; //String to be tested
        String[] str = input.split(" "); // String put into an array

        Map<String, Integer> occurrences = new HashMap<String, Integer>();
        Integer oldValue = 0;

        for (String value : str)
        {
            oldValue = occurrences.get(value);
            if (oldValue == null)
            {
                occurrences.put(value, 1); 
            } else
            {
                occurrences.put(value, oldValue + 1);
            }
        }
        occurrences.remove("");

}

目标字符串数组:

[xy, 3, 123, 6, abc, 2, 456, 4, xyz, 2, 98, 3]

【问题讨论】:

  • 你想如何将 hashmap 转换为字符串。不清楚。
  • 这个问题的答案是否完整?然后请接受它作为答案或发布后续问题。谢谢。

标签: java arrays testing hashmap


【解决方案1】:

问题是,如何从哈希图中读取键值对?

那么下面的例子演示了一些简单的读法:

for(String entry : occurrences.keySet()) {
    Integer value = occurrences.get(entry);         
    System.out.println(entry + ":" + value);
}

输出:

xy:3
123:6
abc:2
456:4
xyz:2
98:3

更新:

要获取字符串数组 [key, value, key, value, ...],请使用以下代码:

ArrayList<String> strings = new ArrayList<>();

for(String entry : occurrences.keySet()) {
    strings.add(entry);
    strings.add(""+occurrences.get(entry));
}

String[] asArray = strings.toArray(new String[strings.size()]);

或者没有ArrayList:

String[] asArray = new String[occurrences.size()*2];
int index = 0;

for(String entry : occurrences.keySet()) {
    asArray[index++]=entry;
    asArray[index++]=""+occurrences.get(entry);
}

【讨论】:

  • 不完全是。我需要测试一个字符串,该字符串会生成一个数组,该数组计算一个单词在字符串中出现的次数。我能够在哈希映射中获得预期结果,但现在我需要将其转换为字符串数组,以便我可以根据实际结果对其进行测试。
  • 您能否给我们“实际结果”,以便我们为您提供帮助?否则我们必须猜测,string[] 中的字符串应该具有什么格式。由于您有一个字符串(键)和整数(值),如果您打算将它们存储在单个字符串数组中,则必须以某种格式组合它们。
  • 哦,当然。对于那个很抱歉。在这种情况下,结果应该是:
  • 数组形式:[xy, 3, 123, 6, abc, 2, 456, 4, xyz, 2, 98, 3]
猜你喜欢
  • 1970-01-01
  • 2021-04-14
  • 1970-01-01
  • 2013-04-17
  • 2023-03-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多