sony samsung
sony samsung

Reputation: 35

java grouping issue

I have an arralist of type asset, where asset is a POJO and has its set and get methods.

ArrayList<Asset> assetItems;

each asset has a ratingValue and it can be fetched by

assetItems.get(i).getratingValue();

Now the task is the assetItems should be grouped based on their rating value . Could some one help me on this

For Example Initially if the ratingvalue of the items in the arraylist are a c g a j c

then the output should be a a c c g j

Upvotes: 0

Views: 114

Answers (4)

Jean Logeart
Jean Logeart

Reputation: 53829

You should try something like:

Map<Integer, List<Asset>> groupedAssets = new HashMap<Integer,  List<Asset>>()
for(Asset asset : assetItems) {
    int ratingValue = asset.getratingValue();
    List<Asset> assets = groupedAssets.get(ratingValue);
    if(assets == null) { // this rating value has never been retrieved before
        assets = new ArrayList<Asset>();
        groupedAssets.put(ratingValue, assets);
    }
    assets.add(asset);
}

The resulting Map contains the list of Asset grouped by ratingValue

Upvotes: 1

Guillaume Polet
Guillaume Polet

Reputation: 47608

If you mean grouping, then have a look at Jon Skeet solution. If you mean sorting, then you can use this code:

Collections.sort(assetItems, new Comparator<Asset>() {
    public int compare(Asset a1, Asset a2) {
        return a1.getratingValue().compareTo(a2.getratingValue());
    }
};

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500775

Sounds like a Multimap from Guava is what you want:

Multimap<String, Asset> map = Multimaps.newListMultimap();
for (Asset asset : assetItems) {
    map.put(asset.getRatingValue(), asset);
}

Then you can get all the assets with a particular rating:

for (Asset asset : map.get(someRating)) {
    ...
}

Upvotes: 3

Rajesh Pantula
Rajesh Pantula

Reputation: 10241

you can group Assets based on threshold value like this.

    Class AssetGroup
    {
    int thresholdrating;
    ArrayList<Asset> listAssets;

   // add Asset to group list

   public void add(Asset a)
   {
    this.listAssets = a;
   }

    }

Upvotes: 0

Related Questions