how can i iterate over objects that are already inside a database and update a field?

This is not a scalable design at all. A single calculation is being done several times over. Imagine you had a table of 1 million of these values and you need to fill up the portfolio percentage for all of them, you would essentially be recalculating the total asset value a million times over. This value could instead be cached and updated as and when a new field is added.

In my opinion, the percentage of the asset value in relation to the portfolio, should not even be stored in the database. The reason is that, this value requires frequent updates. For example, everytime we add one asset, we will have to update the percentage for all the values.

This is a value that should be calculated upon request.

We could store a specific value in the database called ‘Total Asset Value’. This would hold the relevant information. Then everytime an op is done to add a new number, we can have a Service that would do

public void setTotalValue() {
    TotalValue+=BigDecimal.valueOf(amount);
    repository.save(totalValue); // this line can be however you want to persist your data
}

The idea is to add to the total value everytime you add a new asset and then when we want to calculate the total value, we can do something like,

public Map<Asset, BigDecimal> getTotalPercentages(List<Asset> assets) {
    for (asset : asset) {
        map.put(asset, asset.value/totalValue);
    }
    return map;
}

This would give you accurate data dynamically and saves on the extra time for insertion to db.

EDIT: after being given some context in the comments, i have re-did another solution.

We could simply have a variable totalValue that grows everytime you add an asset in the seeding stage and at the end of the seeding, you could iterate through all assets and set the percentage for each of them.

int totalValue = 0;
String[] types = new String[]{"Crypto", "Stock"};
for (int i = 0; i < NUM_OF_DESIRED_ASSETS; i++) {
    Random r = new Random();
    int value = r.nextInt(10);
    int index = r.nextInt(2);
    repository.save(new Asset("", "",value, , types[index]));   

    totalValue+=value; 
}

for (asset : assets) {
    asset.setPercentage(asset.value/totalValue);
    repository.save(asset);
}

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top