0

I have a new ArrayList inside a HashMap, but i don't know how to calculate the size of ArrayList inside the HashMap

Map<String, List<fruit>> groupbyregion = new HashMap<>();
for (fruit s : ll) {
    if (!groupbyregion.containsKey(s.getRegionName())) {
        groupbyregion.put(s.getRegionName(), new ArrayList<>());
    }
    groupbyregion.get(s.getRegionName()).add(s);
}
System.out.println("Group by region: " + groupbyregion);
Praveen
  • 1,791
  • 3
  • 20
  • 33
Dhanasekaran Don
  • 294
  • 1
  • 14

1 Answers1

3

You are already using:

groupbyregion.get(s.getRegionName()).add(s);

This calls the add() method of the ArrayList in that map slot. Thus:

groupbyregion.get(s.getRegionName()).size();

gives you the size.

Beyond that: you want to look here for how to create lists within maps in more elegant (java8) ways.

GhostCat
  • 137,827
  • 25
  • 176
  • 248