I'll try to be as clear as possible.
I have N lists of objects. Each object stores an ID field and a value field.
LIST A | ID1   v1  | ID2   v2  | ID3   v3  |
LIST B | ID1   v1' | ID2   v2' | ID3   v3' |
LIST C | ID1   v1''| ID2   v2''| ID3   v3''|
I need to create a hash map
Map<Integer,List<Double>> 
like this:
------------------------
| ID1 |  v1  v1'  v1'' |
| ID2 |  v2  v2'  v2'' |
| ID3 |  v3  v3'  v3'' |
------------------------
For each list, I'm currenty using this code:
object_list.forEach( v -> {
        String id = v.getID();
        Double value = v.getValue();
        if(map.containsKey(id)){
            map.get(id).add(value);
        }
        else{
            List<Double> list = new ArrayList<>();
            list.add(value);
            map.put(id, list);
        }
});
My question: could I perform this operation in a faster way?
Thanks
You can do it very expressively using Java 8's handy computeIfAbsent method:
objectList.forEach( v -> {
    List<Double> doubleList = map.computeIfAbsent(v.getID(), k->new ArrayList<>());
    doubleList.add(v.getValue());
});
Note that this will not necessarily run faster than your original solution. Its advantage is that it is clearer to read.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With