This question already has answers here:
Java associative-array
(15 answers)
Closed 6 years ago.
I'm wondering if arrays in Java could do something like this:
int[] a = new int[10];
a["index0"] = 100;
a["index1"] = 100;
I know I've seen similar features in other languages, but I'm not really familiar with any specifics... Just that there are ways to associate values with string constants rather than mere numeric indexes. Is there a way to achieve such a thing in Java?
You can't do this with a Java array. It sounds like you want to use a java.util.Map.
Map<String, Integer> a = new HashMap<String, Integer>();
// put values into the map
a.put("index0", 100); // autoboxed from int -> Integer
a.put("index1", Integer.valueOf(200));
// retrieve values from the map
int index0 = a.get("index0"); // 100
int index1 = a.get("index1"); // 200
I don't know a thing about C++, but you are probably looking for a Class implementing the Map interface.
What you need is java.util.Map<Key, Value> interface and its implementations (e.g. HashMap) with String as key
To store things with string keys, you need a Map. You can't use square brackets on a Map. You can do this in C++ because it supports operator overloading, but Java doesn't.
There is a proposal to add this syntax for maps, but it will be added for Java 8 at the earliest.
Are you looking for the HashMap<k,v>() class? See the javadocs here.
Roughly speaking, usage would be:
HashMap<String, int> a = new HashMap<String,int>();
a.put("index0", 100);
etc.
java does not have associative arrays yet. But instead you can use a hash map as an alternative.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
In Javascript, We can write statement as below.
var f_names = {
'a' : 'Apple',
'b' : 'Banana'
'c' : 'Carrot'
};
I can call this as f_names['c'] and get output as Carrot.
Is there any equivalent to this in Java instead of Map ? Similar to above ?
We can create an String array as bellow in java.
String[] names= { "Apple","Banana", "Carrot" };
Then can call as names[2] and this will return output as Carrot.
I'm looking for solution like this.
That is not at all conditional statement. It's Javascript object. In Java also there is Map.
Yes, you are just looking for Map in Java. Which stores key value pairs.
Map<String, String> map= new HashMap<String, String>();
map.put("a", "Apple");
map.put("b", "Banana");
And you can retrieve like
String a = map.get("a");// which results "Apple"
Update: If you are looking for other ways
Take a method which returns String. Add switch case inside method and
return the result value.
Take an array of array ex ({{k,v},{},{}}). Iterate to get the
required value.
Update after your latest comment :
(Both JS and Java are languages. if JS can achieve it as above(in simple way), why we use Map for that in Java.)
You are comparing two languages syntax, it's highly impossible to work with same syntax. If you still want to find the same way, the below would be the closest
HashMap<String, String > map = new HashMap<String, String>(){{
put("a", "Apple");
put("b", "Banana");
}};
Not sure about your acceptance of this cheat ;)
Syntax is a bit more complex in Java.
To get the closest equivalent, you can use a TreeMap, which will order its keys (default in this case is lexicographic order):
Map<String, String> names = new TreeMap<String, String>();
names.put("a", "Apple");
names.put("b", "Banana");
names.put("c", "Carrot");
System.out.println(names);
Output
{a=Apple, b=Banana, c=Carrot}
If you really don't want to use a Map, you can use a double-dimensional array.
For instance:
String[][] namesArray = new String[][]{{"a","Apple"},{"b","Banana"},{"c","Carrot"}};
System.out.println(Arrays.deepToString(namesArray));
Output
[[a, Apple], [b, Banana], [c, Carrot]]
Notes
Amongst the many advantages of using a Map is the fact that you can retrieve your values by key, which is probably something of interest given your context. For instance: names.get("A") will return "Apple.
With the array, you will need to retrieve your values by indices. For instance, namesArray[1][1] is "Banana".
Though Map is the thing you would really want, you could also use enums (I can't really help with those; I lack routine) and public static variables:
public final static String a = "Apple";
public final static String b = "Banana";
public final static String c = "Carrot";
Then they would be referencable from anywhere in the program. Say if the variables resided in a class named Fruits, they would be referenced to like this:
Fruits.a
Fruits.b
Fruits.c
This a Javascript Object(Java Script Object Notation) and it is more or less like a key-value pair. In Java this can be achieved by Map interface and the heavily used implementation of this interface is HashMap.
This question already has answers here:
Equivalent of std::vector in Java?
(9 answers)
Closed 9 years ago.
I'm using Java programming language.
C++ has vector<T> and I need the equivalent vector in Java.
I want to convert this code to Java.
Vector<T> a[Maxn]; // Example: string, int, myclass, myvar, ...
int n;
cin >> n;
for(int i=0; i<n; i++)
{
T x, y;
cin >> x >> y;
x--, y--;
v[x].push_back(y);
}
You are probably looking for ArrayList
Resizable-array implementation of the List interface. Implements all
optional list operations, and permits all elements, including null. In
addition to implementing the List interface, this class provides
methods to manipulate the size of the array that is used internally to
store the list.
Something like this:
ArrayList ar = new ArrayList<String>();
ar.add("abc");
You can use List<T>, Java has many better ways, take it easy!
you could Search it...
Have a look at java.util.List. There are many concrete implementations of list including java.util.ArrayList
Here is an example using ArrayList
Note Java Collections e.g. List<T> make use of generics. Below I am using a list of String
List<String> list = new ArrayList<String>();
list.add("some string");
I'm pretty sure that this is the class you are looking for:
java.util.List
If you want something analogous to C++'s std::vector, I would start by looking at the various classes that implement the List interface (http://docs.oracle.com/javase/7/docs/api/java/util/List.html).
Probably the most commonly-used List is ArrayList, which has all the normal operations you would expect - add, get, size, iterator, etc.
Alternatively there is LinkedList, which is useful in its own way, depending on what exactly you're trying to achieve.
EDIT: I do not advocate using java.util.Vector<E>, but since you are coming from a C background, it might give you a warm fuzzy to use the same name. However, you should note (from the Java API)
Unlike the new collection implementations, Vector is synchronized. If a thread-safe implementation is not needed, it is recommended to use ArrayList in place of Vector.
So it's best to use some other implementation of java.util.List<E> -- most common to use java.util.ArrayList<E>
i want to create an LinkedList of couple that the key is a String and the value is an integer ?
LinkedList doesn't have a key. It's a list of elements, not a key/value mapping.
If you want a LinkedList where each element is a pair of Integer/String values, you'll need to pick one of:
Create a generic Pair class
(Ab)use an existing generic class (e.g. Map.Entry)
Create a custom class for your specific scenario
I would suggest the last option as the most sensible one - you'll be able to give it appropriate semantics and names according to the real meaning of the string and the integer. Heck, you'll also be able to avoid boxing the integer, as you can have:
public class WhateverYouCallIt {
private final int firstValue;
private final String secondValue;
// Constructor, properties
}
You can only use Object in a LinkedList., this means you cant use Java Primitives.
However, what you seem to need is a Map structure.
I recommend using java.util.HashMap, it allows you to create a Key, Value pairs.
Example:
HashMap<String,Integer> a = new HashMap<String,Integer>();
a.put("one",1);
a.put("two",2);
System.out.println(a.get("one"));
//prints 1
System.out.println(a.get("two"));
//prints 2
EDIT:
As per your comment, i see you required order, use the following example then:
LinkedHashMap<String, Integer> b = new LinkedHashMap<String,Integer>();
b.put("one",1);
b.put("two",2);
b.put("a",3);
for (String key:b.keySet())
{
System.out.println(b.get(key)); // print 1 then 2 finally 3
}
Hope this is what you were asking (if so, modify your question).
One error is you need Integer instead of int, but as others have pointed out LinkedList doesn't take Key/Value pairs.
I'd imagine a HashMap is what your after. As other have stated, you cannot use a primitive type such as "int" in a library storage class like LinkedList, or ArrayList, you must instead use an object such as "Integer".
HashMap hash = new HashMap();
Read this for more information: http://docs.oracle.com/javase/1.4.2/docs/api/java/util/HashMap.html
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());