【发布时间】: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