Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The best way to static initialization of Maps in google collections

Tags:

java

guava

What is the best way to static initialization of modifiable Maps? I found only

ImmutableMap.of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5)

But this way created immutable map and contains fixed list of parameters.

like image 882
Nawa Avatar asked Aug 31 '12 15:08

Nawa


People also ask

Is Google Maps static or dynamic?

The Google Maps Platform static web APIs let you embed a Google Maps image on your web page without requiring JavaScript or any dynamic page loading. The APIs create an image based on URL parameters sent through a standard HTTP request and allow you to display the result on your web page.

Can maps be static?

Static Maps are the simplest way to show a map on a website or mobile application because they don't require a mapping library or SDK and can be displayed anywhere images can, including in applications or UIs where interactive maps can't be integrated.

What is the maximum number of markers or path vertices supported by the Google Static maps API?

Note: If you choose to specify marker locations using a method that requires geocoding, such as human-readable address strings or polylines, the request is limited to a maximum of 15 markers. This limit applies only to marker locations that require geocoding.


2 Answers

If you do want an of code fashion, you could use:

myMap = Maps.newHashMap(ImmutableMap.of(k1, v1, k2, v2...));

In addition, ImmutableMap.Builder is other choice to create a Map from complex source:

myMap = Maps.newHashMap(new ImmutableMap.Builder<K, V>()
                   .put(k1, v1) //One k-v pair 
                   .putAll(otherMap) //From other Map
                   .put(Maps.immutableEntry(k2, v3)) //From a Map Entry
                   ...
                   .build());

Plus: My code is not original intention of ImmutableMap. If Nawa insists on using Guava library ;)

like image 53
卢声远 Shengyuan Lu Avatar answered Oct 11 '22 04:10

卢声远 Shengyuan Lu


You don't actually need static initialization. What's wrong with the following ?

Map<K, V> map = Maps.newHashMap();
map.put(k1, v1);
map.put(k2, v2);
// More put() calls

// map is now ready to use.

You can create a helper method around it if needed, but you can only create so many different versions (for 1 entry, 2 entries, etc.). At some point it's not helping anymore.

like image 32
Frank Pavageau Avatar answered Oct 11 '22 03:10

Frank Pavageau