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

醉酒当歌 提交于 2019-12-10 09:33:00

问题


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

来源:https://stackoverflow.com/questions/58574792/run-a-series-of-forumulae-against-key-value-pairs-stored-in-a-java-util-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!