• Post Reply Bookmark Topic Watch Topic
  • New Topic

enhanced for loop and generics object value based grouping  RSS feed

 
Mohit Sinha
Ranch Hand
Posts: 125
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi there,

I have custom object House which has attribute like amountand includes another object called Address.
Class House {

double amount;
Address address;
}

This address object comprises of a zipcode.

I get a list object comprising of collection of houses. I have to achieve something like this for every unique zipcode I have to sum the amount of the houses belonging to that zipcode.
Each zipcode can possibly have 1..n number of houses.

Do let me know your thoughts how can i achieve this sort of grouping based on zip code within enhanced for loop and generics approach.


Regards,
 
Balagopal Kannampallil
Ranch Hand
Posts: 136
Firefox Browser Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Mohit,

Please take a look at this tutorial. It will help you resolve your problem.
 
Mohit Sinha
Ranch Hand
Posts: 125
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Did not get the implementation POV. Can you elaborate
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Mohit Sinha wrote:Did not get the implementation POV. Can you elaborate


The tutorial is pretty silly considering that there are several ways to iterate over a String's characters with a foreach loop without writing any new classes at all.

In any case, I would use a Map, with the keys being zip codes and the values being an Integer. For each house (i.e., using an enhanced for loop) loop up its zipcode in the map. If there's no entry, add it, with the number one as the value. If there is already an entry, then add one to it, and put it back into the map.

At the end of all this, you have a map where the keys are zipcodes, and the values are the counts of the houses.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!