I am trying to get all the repetitions of a string from a given ArrayLists. I achieved this by using the following code:
public static void howmany (ArrayList <String> list)
{
for (int i=0; i<list.size();i++)
{
System.out.println(list.get(i)+ ": " + Collections.frequency(list, list.get(i)));
}
}
However, the output is the following:
sorry: 4 bat: 1 sorry: 4 sorry: 4 sorry: 4 train: 2 train: 2 teddy: 2 teddy: 2 ball: 2 ball: 2
The code in the Runner class is :
ArrayList<String> toys = new ArrayList <String>();
String[] toys1 = {"sorry", "bat", "sorry", "sorry", "sorry", "train", "train", "teddy", "teddy", "ball", "ball"};
for (int i=0; i<toys1.length;i++)
{
toys.add(toys1[i]);
}
Toys.howmany(toys);
Is there a way that the output doesn't repeat the words? For example, that it just says:
sorry: 4, bat: 1, train: 2, teddy: 2, ball: 2
I am a beginner and I am still trying to learn java logic!
Aucun commentaire:
Enregistrer un commentaire