I have a non-static class in Java that has a static hashmap field. The hashmap should be initialized with some key-value pairs generated by code. The hashmap is not to be changed after that.
How should this be achieved? Should I just create a static init method and make sure to run this once before using the class, or are there better ways of doing it?
You can use a static initializer block in your class.
e.g.
private static Map<String, String> myMap;
static {
HashMap<String,String> map = new HashMap<String,String>();
map.put("foo","bar");
myMap = Collections.unmodifiableMap(map);
}
You can easily create immutable maps with Google Guava library:
private static Map<String, String> map = ImmutableMap.of(
"key1", "value1",
"key2", "value2");
If you want to use it for many values then builder() is provided.
Related
I've been trying to create a class that will model a scenario I've come up with. It will involve a map with string keys and values.
I need to create an instance variable used to reference the map object, and a constructor that creates the empty map and assigns it to the map instance variable.
I've been messing around with map objects but not creating a class using them, and I've hit a mental block!
What's the proper way to actually get a map object?
public class TheClass {
private Map<String, String> theMap;
public TheClass() {
theMap = new HashMap<>();
}
}
public class Demo {
Map<String,String> map = null;
public Demo()
{
map = new HashMap<String,String>();
}
}
If you want to use HashMap which is Map implementation you can do it like that:
Map<String, String> map = new HashMap<String, String>();
or
Map<String, String> map = new HashMap<>();
in Java 7.
You can also use other implementations like TreeMap.
You can use the HashMap which is an implementation of Map
http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html
Map<String,String> map = new HashMap<String,String>();
map.put("key1", "Value1");
map.put("Key2", "Value2");
How Can I instantiate a HashMap to put collections and objects?.
//it's wrong
Map<String,?>params=new HashMap<String,? >
List<Person> lstperson=getPerson();
params.put("person",lstperson);
params.put("doc",objectDoc);
params.put("idSol",new Long(5));
service.method(params);
//method
public void method(Map<String, ?> params);
Declare the hash map as
Map<String,Object> params = new HashMap<String,Object>();
You can keep the declaration of
public void method(Map<String, ?> params);
as it is, as long as the method only every tries to read from the map.
All classes in Java extends Object. so you can use Object for a value type in a map, like
Map<String, Object> params = new HashMap<String, Object>
You need to change
Map<String,?>params=new HashMap<String,? >
to like this
Map<String,Object>params=new HashMap<String,Object>()
But its not good practice to put all type of objects into single map. Better you can create POJO and add it to map.
I cam here for substitute in Kotlin
You can declare in kotlin as :-
val map: Map<String, Any?>
This question already has answers here:
How to swap keys and values in a Map elegantly
(9 answers)
Closed 9 years ago.
I want to write a method which will take a map as parameter and replace the keys and values of that map by values and keys. I am trying to do it like this:
public class HashMapKeyValueInterchange{
public static Map<String, String> getMyMap(ConcurrentHashMap<String, String> m){
Map<String, String> map2 = new HashMap<String, String>();
for(Entry<String, String> e:m.entrySet()){
map2.put(e.getValue(), e.getKey());
}
return map2;
}
public static void main(String[] args) {
ConcurrentHashMap<String, String> map1 = new ConcurrentHashMap<String, String>();
map1.put("ajay", "btech");
map1.put("manas", "mca");
map1.put("ashu", "mba");
}
}
Using this method I can get a new map(map2) with exchanged key and values, but I want map1 to be exchanged
It is availabe, no need to reinvent the wheel, if you use google collection library Guava then you can use BiMap<K,V>.
It is a map that preserves the uniqueness of its values as well as
that of its keys. This constraint enables bimaps to support an
"inverse view", which is another bimap containing the same entries as
this bimap but with reversed keys and values.
Implementation of BiMap are EnumBiMap, EnumHashBiMap, [HashBiMap][2], ImmutableBiMap
Use this code
public static ConcurrentHashMap<String, String> getMyMap(ConcurrentHashMap<String, String> m){
ConcurrentHashMap<String, String> map2 = new ConcurrentHashMap<String, String>();
for(Entry<String, String> e:m.entrySet()){
map2.put(e.getValue(), e.getKey());
}
return map2;
}
public static void main(String[] args) {
ConcurrentHashMap<String, String> map1 = new ConcurrentHashMap<String, String>();
map1.put("ajay", "btech");
map1.put("manas", "mca");
map1.put("ashu", "mba");
map1 = getMyMap(map1);
}
If the question is if the code works, the answer is yes. Some comments:
If you want your code tested, you need to call getMyMap with map1 or other adequate parameter.
If you want to see any output, you need to write something like System.out.println( getMyMap( map1 ) );
I'd strongly recommend to use Map instead of ConcurrentHashMap as getMyMap's 1st parameter type, so the function is more general an works with other maps.
To make your code even more general, make it:
public static <K,V> void getMyMap(Map<V,K> output,Map<K,V> input) {
for(Entry<K,V> e: input.entrySet() ) {
output.put(e.getValue(), e.getKey());
}
}
This will accept a bigger variety of Map's and store the output in any type of Map is passed as the first parameter. Example:
getMyMap(new TreeMap<String,String>(),map1);
getMyMap(new HashMap<String,String>(),map1);
A final point is that you don't specify a behavior when values are repeated. The assumption above is that either this case does not occur or that any key in the input map is acceptable as value in the output one.
BiMap is a good choice for this kind of operation
A BiMap is a Map that
allows you to view the "inverse" BiMap with inverse()
ensures that values are unique, making values() a Set
BiMap.put(key, value) will throw an IllegalArgumentException if you attempt to map a key to an already-present value. If you wish to delete any pre-existing entry with the specified value, use BiMap.forcePut(key, value) instead.
BiMap<String, Integer> userId = HashBiMap.create();
String userForId = userId.inverse().get(id);
Look here for more information
Okay so can i achive this somehow:
String myString = "someString";
Class myClass = myString.getClass();
HashMap<mClass, Integer> = new HashMap<myClass, Integer>();
So i would like to create a new hashmap, with class type of the key of my variables like Integer or String...
This is not possible. I'll walk you through the possibilities.
You could create a helper method, using generics. This will work because of all generics are compiled into simple Objects.
public static <T> Map<T, Integer> createMap(Class<T> cl)
{
return new HashMap<T, Integer>();
}
Now, you could use it like this:
Map<String, Integer> map = createMap(String.class);
However, this will require you to know what T is at compile time. So this won't work:
String str = "Test";
Class cl = str.getClass();
Map<String, Integer> map = createMap(cl); // Doesn't compile.
So, to conclude, this helper method isn't worth anything, because you could simply write:
Map<String, Integer> map = new HashMap<String, Integer>();
Due to type erasure this would not work.
A possible (but more verbose way) is to create a factory method that returns a Map based on the passed argument, eg:
MapFactory.create(String.class);
EDIT: In answer to #millimoose comment about this being not different from direct instantiation (which is true):
You could try to implement your own Map or decorate or extend the HashMap implementation so that it retains type information.
This question already has answers here:
Initializing Hashtables in Java?
(10 answers)
Closed 5 years ago.
Is there a way to write a static final Hashtable in java in key value pairs just like you can initialize a string array conveniently as :
String [] foo = {"A","AB"};
Basically what I mean is not having to write the words "put" for key:value pairs but instead may be something like:
Hashtable<String, String> foo = {"JJ":"222","KK":"222"}
which IMO looks more elegant.
(I know the initialization would need to be in a static block. I am leaving that out for now)
An anonymous inner class would give you double brace initialization, which is useful in some cases:
static final Map<String, String> map = new HashMap<String, String>() {{
put("foo", "bar");
put("x", "y");
}};
In any case, #michael667's answer is probably the best
You can use guava's ImmutableMap:
map = ImmutableMap.of(key1, value1, key2, value2);
These convenience methods exist for one to five elements. If you need more, you can use an ImmutableMap.Builder:
static final ImmutableMap<String, Integer> WORD_TO_INT =
new ImmutableMap.Builder<String, Integer>()
.put("one", 1)
.put("two", 2)
.put("three", 3)
.build();
No, Java doesn't have map literals, but it does have array literals.
static final Map<String, String> map;
static {
map = new HashMap<String, String>();
String[][] pairs = {
{"foo", "bar"},
{"x", "y"}
};
for (String[] pair : pairs) {
map.put(pair[0], pair[1]);
}
}
Of course this doesn't really add anything to the straightforward copy and paste put solution, and it doesn't work well if your key and value types aren't the same.
No, you're looking for something like C#'s collection initializers, which doesn't currently exist in Java.
You can use an anonymous class to save a little typing, but you still have to write put.