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);
Related
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" ]
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>.
I'm "translating" a PHP class in Java.
I've a function that takes a key and checks if it's in the $_POST array.
How could I do a similar thing from a class Java method?
Java doesn't support associative arrays. If you're using a HashMap:
HashMap hMap = new HashMap();
//(...)
ht.put("key","One");
ht.containsKey("key"); // returns true
If you're using a hashtable:
Hashtable ht = new Hashtable();
//(...)
ht.containsKey("key");
Unless you mean how to access POST parameters, then check this question and this documentation
Look up request.getParameter()
http://www.roseindia.net/jsp/GetParameterMethodOfRequest.shtml
How do I convert LinkedHashMap to java.util.HashMap in groovy?
When I create something like this in groovy, it automatically creates a LinkedHashMap even when I declare it like HashMap h = .... or def HashMap h = ...
I tried doing:
HashMap h = ["key1":["val1", "val2"], "key2":["val3"]]
and
def HashMap h = ["key1":["val1", "val2"], "key2":["val3"]]
h.getClass().getName() still comes back with LinkedHashMap.
LinkedHashMap is a subclass of HashMap so you can use it as a HashMap.
Resources :
javadoc - LinkedHashMap
Simple answer -- maps have something that looks a lot like a copy constructor:
Map m = ['foo' : 'bar', 'baz' : 'quux'];
HashMap h = new HashMap(m);
So, if you're wedded to the literal notation but you absolutely have to have a different implementation, this will do the job.
But the real question is, why do you care what the underlying implementation is? You shouldn't even care that it's a HashMap. The fact that it implements the Map interface should be sufficient for almost any purpose.
He probably got caught with the dreaded Groovy-Map-Gotcha, and was stumbling around in the wilderness of possibilities as I did for the entire afternoon.
Here's the deal:
When using variable string keys, you cannot access a map in property notation format (e.g. map.a.b.c), something unexpected in Groovy where everything is generally concise and wonderful ;--)
The workaround is to wrap variable keys in parens instead of quotes.
def(a,b,c) = ['foo','bar','baz']
Map m = [(a):[(b):[(c):1]]]
println m."$a"."$b"."$c" // 1
println m.foo.bar.baz // also 1
Creating the map like so will bring great enjoyment to sadists worldwide:
Map m = ["$a":["$b":["$c":1]]]
Hope this saves another Groovy-ist from temporary insanity...
HashMap h = new HashMap()
h.getClass().getName();
works. Using the [:] notation seems to tie it to LinkedHashMap.
What is the most straightforward way to create a hash table (or associative array...) in Java? My google-fu has turned up a couple examples, but is there a standard way to do this?
And is there a way to populate the table with a list of key->value pairs without individually calling an add method on the object for each pair?
Map map = new HashMap();
Hashtable ht = new Hashtable();
Both classes can be found from the java.util package. The difference between the 2 is explained in the following jGuru FAQ entry.
You can use double-braces to set up the data. You still call add, or put, but it's less ugly:
private static final Hashtable<String,Integer> MYHASH = new Hashtable<String,Integer>() {{
put("foo", 1);
put("bar", 256);
put("data", 3);
put("moredata", 27);
put("hello", 32);
put("world", 65536);
}};
Also don't forget that both Map and Hashtable are generic in Java 5 and up (as in any other class in the Collections framework).
Map<String, Integer> numbers = new HashMap<String, Integer>();
numbers.put("one", 1);
numbers.put("two", 2);
numbers.put("three", 3);
Integer one = numbers.get("one");
Assert.assertEquals(1, one);
import java.util.HashMap;
Map map = new HashMap();
What Edmund said.
As for not calling .add all the time, no, not idiomatically. There would be various hacks (storing it in an array and then looping) that you could do if you really wanted to, but I wouldn't recommend it.
And is there a way to populate the table with a list of key->value pairs without individually calling an add method on the object for each pair?
One problem with your question is that you don't mention what what form your data is in to begin with. If your list of pairs happened to be a list of Map.Entry objects it would be pretty easy.
Just to throw this out, there is a (much maligned) class named java.util.Properties that is an extension of Hashtable. It expects only String keys and values and lets you load and store the data using files or streams. The format of the file it reads and writes is as follows:
key1=value1
key2=value2
I don't know if this is what you're looking for, but there are situations where this can be useful.
It is important to note that Java's hash function is less than optimal. If you want less collisions and almost complete elimination of re-hashing at ~50% capacity, I'd use a Buz Hash algorithm Buz Hash
The reason Java's hashing algorithm is weak is most evident in how it hashes Strings.
"a".hash() give you the ASCII representation of "a" - 97, so "b" would be 98. The whole point of hashing is to assign an arbitrary and "as random as possible" number.
If you need a quick and dirty hash table, by all means, use java.util. If you are looking for something robust that is more scalable, I'd look into implementing your own.
Hashtable<Object, Double> hashTable = new Hashtable<>();
put values
...
get max
Optional<Double> optionalMax = hashTable.values().stream().max(Comparator.naturalOrder());
if (optionalMax.isPresent())
System.out.println(optionalMax.get());