Is there any way to access Java map like C++?
In C++, the following code snippet works:
map<string, int> myMap; string str = "okay"; myMap[str] = 69; myMap[str]++; cout<<myMap[str]<<endl;
the above code works perfectly and shows 70 in console.
Is there anything like that in Java?
Advertisement
Answer
Yes and no.
Yes, in that obviously you can get a similar result in Java code.
No, in that many of the C++ concepts you use don’t have a direct equivalent in Java, so the Java code will look quite different.
Basic example
On a trivial level the equivalent to map<string,int>
is Map<String, Integer>
. Note that int
can’t be used here, since Java generics don’t support primitive types as type arguments, so you’ll need to use the wrapper. In code that difference will be mostly invisible, thanks to auto-boxing.
But Map
is an interface, so you’ll need to specify which implementation you want to use. HashMap
is the default choice, if you have no specific requirements.
Map<String, Integer> myMap = new HashMap<>();
Java doesn’t have (custom) operator overloading, so you’ll need to call .put()
to add a value to the map:
String str = "okay"; myMap.put(str, 69); // nice
And due to the same issue and since Integer
objects are immutable, the following line will look a bit uglier in Java:
myMap.put(str, myMap.get(str) + 1);
Printing is then simply this:
System.out.println(myMap.get(str));
Alternative 1: Use compute
One alternative (that I personally find overkill) is to use the compute
method and a lambda expression like this (there’s also computeIfPresent
and computeIfAbsent
with the obviuos restrictions):
myMap.compute(str, (k, v) -> v+1);
Alternative 2: use AtomicInteger
(or int[]
) instead of Integer
Another alternative is to use something like AtomicInteger
as your value. In this case you wouldn’t really care about the fact that AtomicInteger
has atomic operations, but use it as a “mutable Integer
” in a way.
Map<String, AtomicInteger> myMap = new HashMap<>(); String str = "okay"; myMap.put(str, new AtomicInteger(69)); myMap.get(str).incrementAndGet();
Since AtomicInteger
is mutable, you don’t have to change the map to change what value it points to. Some people use a one-element array (like new int[1]
) to get a similar effect. I’d consider both uses a bit hacky and personally prefer the more explicit AtomicInteger
:
Map<String, int[]> myMap = new HashMap<>(); String str = "okay"; myMap.put(str, new int[] { 69 }); myMap.get(str)[0]++;