我的問題有點不同。我有一個包含一些路由的ArrayList。對於前:查找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.");
[查找ArrayList()中最常見的字符串的可能的副本)(http://stackoverflow.com/questions/22989806/find-the-most-common-string-in-arraylist) – Joe
@Joe OP要求對於這個問題中最常見的字符串(如果它們出現的話,會有多個字符串)。 – user6904265