JAVA - Creating an Acceleration Hash Map

I will try to be as clear as possible.

I have N object lists. Each object stores an identifier 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 use this code as follows:

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 is: can I complete this operation faster?

thank

+4
source share
4 answers

You can do this very expressively using the handy computeIfAbsentJava 8 method :

objectList.forEach( v -> {
    List<Double> doubleList = map.computeIfAbsent(v.getID(), k->new ArrayList<>());
    doubleList.add(v.getValue());
});

Please note that this will not necessarily work faster than your original solution. Its advantage is that it is easier to read.

+8
source

Using the guava multimap would be simpler.

ListMultimap<Integer, Double> multimap = ArrayListMultimap.create();

put(), guava :

String id = v.getID();
Double value = v.getValue();
multimap.put(id, value);

id , , .

+6

: ?

?

, ; , 10 . ?

; , ?

, , , .

, ; , . , . : , . , , ; , !

: . , !

+3

If for N elements you mean that their number is fixed, you can create a map of a size that does not expand when filled.

Map<Integer,List<Double>> map = new HashMap<Integer,List<Double>>(N, 1);
+1
source

Source: https://habr.com/ru/post/1664316/


All Articles