Run a series of forumulae against key/value pairs stored in a java.util.List

Viewed 100

Say I have a List containing components like the following:

[
    {
        "id": 1,
        "name": "Displacement",
        "value": 200
    },
    {
        "id": 2,
        "name":"Time",
        "value": 120
    },
    {
        "id":3,
        "name":"Mass",
        "value": 233
    },
    {
        "id":4,
        "name": "Acceleration",
        "value": 9.81
    },
    {
        "id": 5,
        "name":"Speed of Light",
        "value": 300000000
    }
]

Each component is an object of the following class:

class Component {
    Integer id;
    String name;
    Long value;

    // necessary getters and setters
}

I need to get the following metrics from the above List: Velocity (Displacement/Time), Force (Mass * Acceleration) and Energy (Mass * Speed of Light^2)

What is the most of doing this? I could stream the list and filter for the necessary components like so:

Double calculateVelocity() {
    Component displacement = list.stream().filter(c -> c.getName().equals("Displacement")).findFirst().orElseThrow(//throw err);
    Component time = list.stream().filter(c -> c.getName().equals("Time")).findFirst().orElseThrow(//throw err);
    return displacement.value / time.value;
} // repeat for other metrics

This would be tedious as the final implementation would have quite a lot more metrics to calculate at a time. Is there any better way?

Thanks

0 Answers
Related