I\'ve these code for searching occurrence in Array-List but my problem is how I can get result out side of this for loop in integer type cause I need in out side , may be th
I would sort the list first to avoid going thru the whole list with Collections.frequency every time. The code will be longer but much more efficient
List list = new ArrayList();
list.add("aaa");
list.add("bbb");
list.add("aaa");
Map map = new HashMap();
Collections.sort(list);
String last = null;
int n = 0;
for (String w : list) {
if (w.equals(last)) {
n++;
} else {
if (last != null) {
map.put(last, n);
}
last = w;
n = 1;
}
}
map.put(last, n);
System.out.println(map);
output
{aaa=2, bbb=1}