Grab object where key is a certain value - java

Within my java application I have a hashmap that holds a string and an Integer. I'm in a situation where I need to return an object where the key is a certain value. I'm not sure how I would go about doing this. Your support would be greatly appreciated.
public HashMap<String, Integer> loginArenaList = new HashMap();

You need Map#get(Object) method:
loginArenaList.get(key);
BTW, your declaration of map is wrong. You are missing generics type on RHS. And of course, you should declare the reference as private, unless you have strong reasons to use public. Should be:
private Map<String, Integer> loginArenaList = new HashMap<>(); // In Java 7

According to the declared map, your keys are of type String and the object to be retrieved is of type Integer. Assuming that you have the key in the variable "key", all you have to do is use the get method.
loginArenaList.get(key);

Related

Can I define a hashmap differently to it's declaration

What I would like to do is have a map that actually holds values as one thing, but is declared as another e.g. actually hold the value as String, but put/get will use Integer...
Map<String,String> map = new HashMap<String,String>();
I can use this map with
map.put("A","1");
String ret = map.get("A");
but this will get me a String, and I need to 'put' in a String too.
What I would like is for the put/get methods to accept an Integer value (but the map still stores ...
map.put("A",1);
Integer ret = map.get("A");
How can I achieve this?
N.B. this isn't exclusively for String/Integer conversion, but just conversion between any types.
Thanks.
You can use Object as the value type. It can store String, Integer, Double, for that matter almost anything. But you need to be very careful when using Object because you'll have to cast each value you get from the map accordingly(else you'll always get a ClassCastException).
Map<String, Object> map = new HashMap<String, Object>();
FYI, I do not recommended you to use this. Instead be sure what your Map has to hold and have the value type accordingly.
Simply
Map<String,Integer> map = new HashMap<String,Integer>();
You can (but not SHOULD use, really) this critter: https://gist.github.com/eltabo/8953176. Really... it's evil.
Only for educational purpose.
Why should someone want to store a value in a different representation than the value is made out of? You still can create a string out of an integer and reverse after obtaining it from the map, but what is your advantage?

Blank final with Reference type

why we can change a hashMap which is declared as blank final, but we cannot change a primitive type?
for example
if I create a map
final Map<String, String> someMap;
and initialize it in constructor, and still I can put values in this. But same is not the case with primitive
final int a;
I cant change the value of a in this case. can somebody explain this ?
final means it cannot be changed once initialized. You are just declaring the variable but not initializing it, hence it is allowed.
So doing this is valid
final Map<String, String> someMap;
someMap = new HashMap<String, String>();
But if you try to assign another value to it post initialization then compiler should throw an error that final variable is already intialized:
final Map<String, String> someMap;
someMap = new HashMap<String, String>();
someMap = new TreeMap<String, String>(); //error here
Note: Also putting/removing values in hashmap does not change the reference of the final variable.
It is just the reference to the map (i.e. the variable someMap) which cannot be changed. The map itself can be changed. You can for example insert values. But you cannot assign a new map to someMap.
When using the final keyword on variables you are saying that the variable can be defined only once. In other words once a value has been assigned to the variable, it cannot be reassigned.
This yields obvious behavior with primitive types but is less obvious with objects. Importantly though when inserting values into a map, the object instance remains the same. This is important to remember when passing objects to methods, and really important when using get/set/clone methods as you may end up with multiple references to the same object, where a change in one place (insert entry into map) may have undefined effects in others.
If the Map in your question is important you can use java.util.Collections.unmodifiableMap(m); to stop people fiddling with it.
*emphasized text*When you write:
final Map<String, String> someMap;
it's important to realise that someMap is a reference, and you're declaring the reference to be final. The actual object is not immutable, but the reference is. Hence you can't change the reference i.e. you can't do:
someMap = anotherMap;
later on.

Is there any KV data structure in Java which accepts key in primitive type?

I need to store information in Key Value manner. But the built-in Map interface cannot fit for my requirement. Java Map requires both Key and Values to be reference, while I need to use primitive value as key.
Is there any data structure something like Map ? Thanks for your help!
Requirement Details:
My server written in Java runs as a daemon listening a tcp port. When a user first connect in, details about the user need to be stored in KV manner, and the second time the user connect in, his details should be able to read from the KV data structure.
I cannot use the user object as key, for it will be destructed when disconnect, and reconstructed in the second connection. The two objects are not the same reference. Integer key doesn't fit for my requirement either for the same reason.
In other words, I need to use value as key, not reference.
Keys could be considered are: UUID(long), id(int) and so on. They are all primitive type.
Still you can go with java Map as wrapper classes are available for all primitive type and java supports auto boxing, So you can use java.util.Map. ex -
Map<Long,Integer> map = new HashMap<Long,Integer>();
long uuid=10; int i= 10;
map.put(uuid,i);
I fail to see why you can't simply wrap your primitive type in it's corresponding non-primitive class and use that as your key in a regular java map.
Map<Integer, Object> map = new HashMap<Integer, Object>();
Integer key = Integer.valueOf(5);
Object test = new Object();
map.put(key, test);
Object test2 = map.get(Integer.valueOf(5));
test.equals(test2); // will be true
No, collections don't suport primitive types, so you have to use a wrapper classes for primitive types or array.
What you are looking for is called a Hashmap.
Hashmap<Long, Integer> dict=new HashMap<Long, Integer>();
dict.put(24,10);
dict.put(13,63);
dict.get(13); // Equals 63
Essentially, a HashMap will take the first argument as a key, and the second as the value, exactly as you requested. You can assign any type, including a Long for larger integers than normal, although you can't pass primitives. Still, this hasn't ever been an issue for me.
various implementations exist elsewhere, but not in the standard java library. See for example LongHashMap.
The HashMap class is fine for using key-value pairs, but there is no such thing which accepts primitive types.
We'll still try to use a primitive type in the context of a Map.
HashMap<Integer, V> map = new HashMap<>();
map.put(12, someV);
As we write map.put(12, someV), in fact, one cannot use a primitive type as the first argument of the method 'put' of class java.util.Map. But in Java, the integer '12' will automatically be 'converted' (auto-boxed) into the correspondenting wrapper class, in this case Integer.
So that means that there is actually an object of type Integer in the HashMap, but it is reflected as an int.

Cannot Create an LinkedList<String, int>

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

Eclipse Warning with Java HashMap

Eclipse is saying "HashMap is a raw type" When I use the following code
HashMap = new HashMap();
Any idea what could be wrong?
Eclipse will give you that warning when you use a non-Generic HashMap using Java 5 or newer.
See Also: The Generics Lesson in Sun's Java Tutorials.
Edit: Actually, here, I'll give an example too:
Say I want to map someone's name to their Person object:
Map<String, Person> map = new HashMap<String, Person>();
// The map.get method now returns a Person
// The map.put method now requires a String and a Person
These are checked at compile-time; the type information is lost at run-time due to how Java implements Generics.
Nothing wrong exactly, but you are missing out on the wonderful world of generics. Depending on what constraints you want to place on the types used in your map, you should add type parameters. For example:
Map<String, Integer> map = new HashMap<String, Integer>();
That is missing generics, i.e. . If you don't know thise then set the eclipse compiler to java 1.4
Try
HashMap<String,Integer> map = new HashMap<String,Integer>();
instead (obviously replacing the key type (String) and value type (Integer)).
That usually means you're mixing generic code with non-generic code.
But as your example wont even compile its rather hard to tell....
It's missing the generic type. You should specify the key-value generic pair for your map. For instance, the following is a declaration that instantiates a HashMap with String type key and Integer type value.
Map<String, Integer> map = new HashMap<String, Integer>();
All of these are valid answers, you could also use the #SurpressWarnings annotation to get the same result, without having to resort to actual generics. ;)
hashmap is a raw type and hence should be parameterised ie
what ever the data we get through the haspmap function their type must be declared for getting its functions
for example
HashMap<String, Integer> map = new HashMap<String, Integer>();
With the latest Java, you do not have to explicitly mention the variable types in declaration. You can simply put:
= new HashMap<>();

Categories

Resources