Like String s="sample" in java.How to declare and assign values to a hashMap in one step. Also is it possible to assign more set of values at a time using put function in hashMap.
Yes, it is possible. you can use the below code
HashMap<String,String> instruments = new HashMap<String, String>() {
{
put("test","test");
put("test1","test1");
}
};
Use a library like Google Guava which has lots of utilities to instantiate HashMaps. It is also possible doing anonymous inheritance like this:
Map<String, Object> map = new HashMap<String, Object>() {{
put("Test", "Test1");
put("Test", "Test1");
}};
But I wouldn't recommend it.
such constructs do not exist in good ol' java.
On one hand, you can use property files format for that. You can save your map as a something-separated key-value pairs in a string or a file, and read them in a loop filling your map with each pair.
on the other hand, if you really need that + possible type-checking, you can look at modern dynamic JVM languages, like Groovy or Scala.
there you can use the code as it is:
def map = [ a:1, b:23, c:"aasdasd" ]
Related
Given a Map, how can I make an immutable map using Guava? I know one way through Collections.unmodifiableMap but is there any other way using Guava?
Map<String, String> realMap = Maps.newHashMap();
realMap.put("A", "B");
// any other alternative?
Map<String, String> unmodifiableMap = Collections.unmodifiableMap(realMap);
I am populating my realMap with some entries and then I need to make it Immutable so that no one can modify it. I am just trying to see if there is any alternative using Guava? I did some search but I cannot find it.
You're looking for ImmutableMap.copyOf():
ImmutableMap<String, String> immutableMap = ImmutableMap.copyOf(realMap);
Keep in mind that, as opposed to unmodifiableMap() which only creates a wrapper to its argument, this actually copies it to a new map. That can mean a slight performance hit, but it also means there's no possibility of the map being modified accidentally through realMap.
I'm trying Kotlin and I've encountered a small problem that I can't resolve.
When I have the following construction I can put elements into the map:
val map = HashMap<String, String>()
map["asd"] = "s"
map.put("34", "354")
However when I create a map with the Map interface I can only read them, what I'm doing wrong ?
val map: Map<String, String> = HashMap<String, String>();
map.put("24", "34") //error
map["23"] = "23" //error
Or maybe I'm confusing something about interfaces in Kotlin ?
In the first example map gets the type of HashMap,
in the second example you cast it to the Interface Map.
Map is a readonly map, there is no put/set, see here
In order to be able to edit the map, you should use MutableMap
When working with kotlin collections, one important consideration is that, kotlin categorizes its collections as mutable and immutable. this is in contrast to java, where no such categorization exists.
In kotlin for most collections you have a base interface which only supports read-only methods. In your case Map<K,V is an example of that, from the docs
Methods in this interface support only read-only access to the map;
read-write access is supported through the MutableMap interface.
this is the reason for error when you try to modify the map after val map: Map<String, String> = HashMap<String, String>();, even though the actual object is of type HashMap<String,String>, but the map reference is of type Map<String,String>, which will only provide read only operation.
Now if you use a class which implements MutableMap<K,V> then you can put values in map as well. this is the case with val map = HashMap<String, String>(), since here type of map is HashMap<K,V>, which extends MutableMap<K,V> and hence is mutable.
The question is pretty much self-explanatory. I have a data structure (I mentioned a HashMap but it could be a Set or a List also) which I initially populate:
Map<String, String> map = new HashMap<String, String>();
for( something ) {
map.put( something );
}
After the structure has been populated, I never want to add or delete any items:
map.freeze();
How could one achieve this using standard Java libraries?
The best you can do with standard JDK libraries is Collections.unmodifiableMap().
Note that you must drop the original map reference, because that reference can still be accessed and changed normally. If you passed the old reference to any other objects, they still will be able to change your map.
Best practice:
map = Collections.unmodifiableMap(map);
and make sure you didn't share the original map reference.
It sounds like you would do very well with Guava's ImmutableMap. Which allows use of the Builder pattern to assemble and "freeze".
Wrap it in a class and make it immutable. For example:
public class ImmutableMapWrapper {
private Map<String, String> map = new HashMap<String, String>();
public ImmutableMapWrapper() {
for( something ) {
this.map.put( something );
}
}
}
Create an immutable HashMap:
HashMap <MyKey, MyValue> unmodifiableMap = Collections.unmodifiableMap(modifiableMap);
JavaDoc here.
Also, I think the Google data collections utils (Guava???) has an ImmutableMap type already.
I need to make an int array using Strings instead of ints.
EX: int["number2"] = 0; instead of int[2] = 0;
Does anyone know how to do this?
Thanks for your time.
you could use a HashMap - see here for more info!
Java doesn't support associative arrays, but you could use a HashMap:
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("key1", 25);
map.put("key2", 4589);
map.get("key1") will return 25.
You are not looking for an array but for an associative array.
In Java, in practice, every class that implements Map can be used as an associative container, since they can map keys to values (TreeMap<K,V>, HashMap<K,V>, and so on)
This syntax looks very like a map in Groovy, In Java, you could use something like a Map<String, Integer>.
Such as in PHP:
<?php
$a = 'hello';
$$a = 'world';
echo $hello;
// Prints out "world"
?>
I need to create an unknown number of HashMaps on the fly (which are each placed into an arraylist). Please say if there's an easier or more Java-centric way. Thanks.
The best you can do is have a HashMap of HashMaps. For example:
Map<String,Map<String,String>> m = new HashMap<String,Map<String,String>>();
// not set up strings pointing to the maps.
m.put("foo", new HashMap<String,String>());
Its not called variable variables in java.
Its called reflection.
Take a look at java.lang.reflect package docs for details.
You can do all such sorts of things using reflection.
Bestoes,
jrh.
Java does not support what you just did in PHP.
To do something similar you should just make a List<Map<>> and store your HashMaps in there. You could use a HashMap of HashMaps.
A 'variable variable' in Java is an array or List or some sort of data structure with varying size.
No. You would do something like
List<Map<String,String> myMaps = new ArrayList<Map<String,String>>()
and then in your loop you would do:
Map<String,String> newMap = new Hashtable<String,String>();
//do stuff with newMap
myMaps.add(newMap);