【发布时间】:2017-03-30 14:14:48
【问题描述】:
我的问题有点不同。我有一个包含一些路由的 ArrayList。例如:
[ACD, CDE, DEB, EBJ, BJK, JKO, ACD, CDE, DEX, EXB, XBJ, BJK, JKO, KOL]
当我使用 HashMap 进行计数时,它只打印一个字符串:
Most common route: ACD
This route repeats 2 times.
没错,但是字符串 CDE、BJK 和 JKO 也重复了 2 次。由于我是编程初学者,请您告诉我我必须在代码中更改哪些内容,以便打印所有最常见的路线(字符串)。
代码如下:
Map<String, Integer> stringsCount = new HashMap<>();
for(String string: listaRuta)
{
Integer count = stringsCount.get(string);
if(count == null) count = new Integer(0);
count++;
stringsCount.put(string,count);
}
Map.Entry<String,Integer> mostRepeated = null;
for(Map.Entry<String, Integer> e: stringsCount.entrySet())
{
if(mostRepeated == null || mostRepeated.getValue()<e.getValue())
mostRepeated = e;
}
if(mostRepeated != null)
System.out.println("Most common route: " + mostRepeated.getKey());
System.out.println("This route repeats " + mostRepeated.getValue() + " times.");
【问题讨论】:
-
@Joe OP 要求提供此问题中最常见的字符串(如果出现则不止一个字符串)。
标签: java string list arraylist hashmap