Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAVA - Speedup hash map creation

Tags:

java

hashmap

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

like image 326
Fab Avatar asked Dec 01 '22 12:12

Fab


1 Answers

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.

like image 106
Klitos Kyriacou Avatar answered Dec 12 '22 15:12

Klitos Kyriacou