Android - Is it possible to have a lookup array? - android

I know there's an answer to this, but i'm not sure what to search and cannot remember the right phrasing.
Essentially what i mean, i'm being passed an integer. I want to search through an array using this integer to return a string value.
E.g.
I'm given the number 2. My lookup array looks like so:
array.add(1, "Auckland")
array.add(2, "Wellington")
array.add(3, "Bay of Plenty")
When i iterate through the array, i want to return "Wellington".
Can someone point me in the right direction please? :)

Hi you should declare a HashMap of Integer String:
HashMap<Integer, String> map= new HashMap<Integer, String>();
map.put(1, "Auckland");
map.put(2, "Wellington");
map.put(3, "Bay of Plenty");
And then to get the String you should call the HashMap using the key:
String yourString = map.get(1);

Related

How to sort a HashMap if both have same key?

I have a hashmap which have same value but different key.I want to sort them how this will possible?
Image of this Hashmap is below
HashMap Image
public static HashMap<String,Integer> entry = new HashMap<>();
Use TreeMap for sorting by key
Use below code for sorting by value:
private static HashMap sortByValues(HashMap map) {
List list = new LinkedList(map.entrySet());
// Defined Custom Comparator here
Collections.sort(list, new Comparator() {
public int compare(Object o1, Object o2) {
return ((Comparable) ((Map.Entry) (o1)).getValue())
.compareTo(((Map.Entry) (o2)).getValue());
}
});
// Here I am copying the sorted list in HashMap
// using LinkedHashMap to preserve the insertion order
HashMap sortedHashMap = new LinkedHashMap();
for (Iterator it = list.iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next();
sortedHashMap.put(entry.getKey(), entry.getValue());
}
return sortedHashMap;
}
Please check here for details.
Here some good example for sorting HashMap in Java by Keys and Values.
HashMap is not meant to keep entries in sorted order, but if you have to sort HashMap based upon keys or values, you can do that in Java. Sorting HashMap on keys is quite easy, all you need to do is to create a TreeMap by copying entries from HashMap. TreeMap is an implementation of SortedMap and keeps keys in their natural order or a custom order specified by Comparator provided while creating TreeMap. This means you can process entries of HashMap in a sorted order but you cannot pass a HashMap containing mappings in a specific order, this is just not possible because HashMap doesn't guarantee any ordering. On other hand, sorting HashMap by values is rather complex because there is no direct method to support that operation. You need to write code for that. In order to sort HashMap by values you can first create a Comparator, which can compare two entries based on values. Then get the Set of entries from Map, convert Set to List and use Collections.sort(List) method to sort your list of entries by values by passing your customized value comparator. This is similar of how you sort an ArrayList in Java. Half of the job is done by now. Now create a new LinkedHashMap and add sorted entries into that. Since LinkedHashMap guarantees insertion order of mappings, you will finally have a Map where contents are sorted by values.
Detailed information over here:
https://www.java67.com/2015/01/how-to-sort-hashmap-in-java-based-on.html

Android mapping does not work

Hi I have to send map to server and the server will get information from that. I'm having two piece of code for mapping first is(name and key are variables)
String user = "{ 'id':" + userId +","+"'response':{'id':"+userId+",'access':"+"'"+name+":"+key+"'"+"}}";
Map<String, Object> userMap = new Gson().fromJson(user, new TypeToken<HashMap<String, Object>>() {}.getType());
Set<String> keys = userMap.keySet();
for (String i:keys){
Log.d("user",i+" "+userMap.get(i));
}
here I concat required string and parse it and then convert it into map . This piece of code had worked. And my second set of code is
String user1 = "{id="+userId+", access="+""+name+":"+key+""+"}";
Map<String,Object> tuc = new HashMap<>();
tuc.put("id",userId);
tuc.put("access","");
Set<String> key = tuc.keySet();
for (String i:key){
Log.d("user",i+" "+tuc.get(i));
}
this code is not working,that mean server is not accepting this code. But when I print key value pairs the results are same for both codes. My lead doesn't like to use first piece of code. Can any one explain why,I'm struck in this for past two days. Thank you.Sorry for my poor English.
In Java, HashMap can only accept <key, value> pairs. It is not like Json, which in your case is in {key1:value1, key2:value2, ...} format.
Therefore, if you are intended to convert its format from {key1:value1, key2:value2, ...} into <key, value>. My suggestion is combining value2, value3, ... into an object (like String) as the value and value1 as the key.
See https://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html for more details.

store two string and one integer in shared preference using hashmap

I want to store three values in shared preference
Can I store integer as third value in hashmap? As i passed null for string, what can i passed for integer?
public HashMap<String, String> getUserDetails(){
HashMap<String, String> user = new HashMap<String, String>();
// user name
user.put(KEY_NAME, pref.getString(KEY_NAME, null));
// user email id
user.put(KEY_PASS, pref.getString(KEY_PASS, null));
user.put(KEY_ID,pref.getInt(KEY_ID,));//what should i pass here??
// return user
return user;
}
you've declared your HashMap() as a map that contains String objects, so, no, you can't really just store an integer in there. However, you can convert the integer to a string if you like. Since getInt() returns a primitive int, you should use the static method Integer.toString(valuetomakeintoastring)
The second value in your call to getInt() is the default value that should be returned if the KEY value is not found in the preferences. Use some value that can't be confused as a valid value for your application.
user.put(KEY_ID,Integer.toString(pref.getInt(KEY_ID,<somedefaultintegervalue>));
Perhaps a HashMap is not the right data structure for you to use here? Perhaps you really need to define a class that contains these values together, then create a HashMap of that class?

Java - Parse - iterate over ParseObject fields

Having a ParseObject object how can I loop through its fields and get the name of the field along with the value of it? This would really help me minimize my code.
Hmm, ParseObject contains key-value pairs, and I think you can't iterate though it. But. I found something called .keySet() method of ParseObject. It returns ... well, the set of keys (excluding createdAt, updatedAt, authData, or objectId). I think you can convert it into an array and iterate trhough it?
Something like this:
Set<String> keySet = parseObject.keySet();
String[] parseKeys = keySet.toArray(new String[keySet.size()]);
for (String key : parseKeys) {
String parseValue = parseObject.get(key);
//do whatever you want
}

compare two HashMap Integer and String

I got two HashMaps with Strings and Integers and both of them carry "20" and 20
When i'm trying to compare them using toString() i always get inequality:
HashMap<String, String> vals = HashMap<String, String>();
HashMap<Integer, Integer> nums = HashMap<Integer, Integer>();
if(nums.get(id).toString() == vals.get("num")) {
Log.i(TAG, "DataBase.updateOrder(): number is the same");
} else {
Log.i(TAG, "DataBase.updateOrder(): number has changed");
}
When i use Integer.valueOf() for String HashMap it works well and they are equal:
if(nums.get(id) == Integer.valueOf(vals.get("num")))
And of course the following record doens't work at all in the way i need:
num.get(id).equals(vals.get("num"))
So the question is why does my first bit of code not work (as i expected)?
use this.equals in your compare the string.
if(nums.get(id).toString().equals(vals.get("num"))) {
Log.i(TAG, "DataBase.updateOrder(): number is the same");
}
you can compare if you parse the String to an int, then you have an integer comparison instead of an string comparison:
if(nums.get(id) == Integer.parseInt(vals.get("num"))) {
Well, it is rather simple:
when you compare by "==" you compare the objects' location in memory. If you want to be sure that "=="
is doing the right thing you need somehow to point one to the other (not the perfect way of saying). Equals on the other hands tries to compute the comparison of the objects' contents.
More about what I have just explained at the link below.
http://www.programmerinterview.com/index.php/java-questions/java-whats-the-difference-between-equals-and/
If you want tor read more about how to implement your own equals on your classes read here.
http://tutorials.jenkov.com/java-collections/hashcode-equals.html
I hope I answered to your question.

Categories

Resources