How to add some value in ArrayList which is inside of HashMap? My bellow code showing 0 sizes of the hash
val hash= HashMap<String, ArrayList<String> >()
hash["bro"]?.add("Ali Umar")
hash["sis"]?.add("Tamanna")
hash["bro"]?.add("Faruk")
hash["sis"]?.add("Aklima")
hash["bro"]?.add("Ab Siddik")
Log.d("Hash", hash.size.toString())
You have to initialize a List and put the key and that initialized List into the HashMap before you can add any more items to the value of a key. In your example code nothing is put into the HashMap and nothing can be added.
Try it like this (or similar)
fun main() {
// initialize the hashmap
val hash = hashMapOf<String, MutableList<String>>()
// put the keys with empty lists into the hashmap
hash.put("bro", mutableListOf())
hash.put("sis", mutableListOf())
// add items to the value (the list) of existing keys
hash.get("bro")?.add("Ali Umar")
hash.get("sis")?.add("Tamanna")
hash.get("bro")?.add("Faruk")
hash.get("sis")?.add("Aklima")
hash.get("bro")?.add("Ab Siddik")
// print size and content
println("Hash size is ${hash.size.toString()}")
println(hash)
}
In the Kotlin Playground this outputs
Hash size is 2
{sis=[Tamanna, Aklima], bro=[Ali Umar, Faruk, Ab Siddik]}
The problem is that the following instructions are just reading from the hashmap but not inserting anything
hash["bro"]
hash["sis"]
so when you create your hashmap with val hash= HashMap<String, ArrayList<String> >() it is empty and "bro" and "sis" do not exist. so it is null and the add function will not be called because of ?. skips execution if the value is null.
so to add something to bro and sis you first have to put values to your hashmap.
hash.put("bro",ArrayList<String>())
hash.put("sis",ArrayList<String>())
this would change your example as follows
val hash= HashMap<String, ArrayList<String> >()
hash.put("bro",ArrayList<String>())
hash.put("sis",ArrayList<String>())
hash["bro"]?.add("Ali Umar")
hash["sis"]?.add("Tamanna")
hash["bro"]?.add("Faruk")
hash["sis"]?.add("Aklima")
hash["bro"]?.add("Ab Siddik")
Log.d("Hash", hash.size.toString())
Related
I've got this structure of the database:
-requests
-userID
-requests
-requestingUserID1 : groupID1
-requestingUserID2 : groupID2
How to delete specific request by HashMap's key? Let's say I have some requestingUserID, and I want to delete it. So far I've got:
val updates = HashMap<String, Any>()
// updates["/requests/${firebaseUser.uid}/friendId"] = FieldValue.delete() // verion 1
updates["/requests/${firebaseUser.uid}/requests.${friendId}}"] = FieldValue.delete() //version 2
// more updates
db
.updateChildren(updates) // error occurs here
// onCompleteListener()
I get the following error:
com.google.firebase.database.DatabaseException: No properties to serialize found on class com.google.firebase.firestore.FieldValue$DeleteFieldValue
The simplest solution to delete a record from a Firebase Realtime Database is to use "removeValue()" method as shown in the following lines of code:
val rootRef = FirebaseDatabase.getInstance().getReference()
val friendIdRef = rootRef.child("requests/${firebaseUser.uid}/requests/${friendId}")
friendIdRef.removeValue().addOnCompleteListener(object : OnCompleteListener<Void?>() {
fun onComplete(task: Task<Void?>) {
if (task.isSuccessful()) {
Log.d(TAG, "Item successfully deleted.")
}
}
})
The delete() method that you are using is apart of the Firestore SDK. While both databases are apart of Firebase, both are two different products, with two different mechanisms.
Iterate over the HashMap using the Iterator.hasNext() method. While
iterating runs , check for the value at that iteration to be equal to
the value specified. The entry value of the Map can be obtained with
the help of entry.getValue() method. If the value matches, remove the
entry of that iteration from the HashMap using remove() method. The
required entry has been successfully removed.
I have mentioned a syntax below :
Iterator>
iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry entry = iterator.next();
if (valueToBeRemoved.equals(entry.getValue())) {
iterator.remove();
}
}
remove() method syntax is:
hashmap.remove(Object key, Object value);
Here, hashmap is an object of the HashMap class.
Remove method takes two types of parameter:
Key: remove the mapping specified.
Value : removes the mapping only if the specified key maps to the specified value.
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
I just want to ask why my HashMap is inserting the same value even if I put it inside a loop?
val parentMap = HashMap<String, Any?>()
val map = HashMap<String, Any?>()
orders.forEachIndexed { i, order ->
map["id"] = order.id
map["productName"] = order.productName
map["quantity"] = order.quantity
Log.i(TAG, "order=$order")
parentMap["data$i"] = map
Log.i(TAG, "map=$parentMap") // This parent map contains a same value from map...
}
Log.i(TAG, "map=$parentMap")
Did I forget something to put??
Any help is appreciated, Thanks.
So what you are doing here is assigning the map object to your parent map. The parent map stores the map object as a whole instead of the data. You will have to create a new 'map' object in every iteration.
I think "map" can be a reference variable. so it will insert the same values
To sum up what everyone said here.
In java and kotlin all objects stored in a heap and all your variables only store references to the objects in heap:
When you are doing this: parentMap["data$i"] = map
Your keys, ex: data1, data2, data3... will point to an instance of the same map which you created here: val map = HashMap<String, Any?>().
So everything that you do to your map:
map["id"] = order.id
map["productName"] = order.productName
map["quantity"] = order.quantity
change only one map that you have.
To fix it you can put your map creation inside the loop.
Or I suggest you to use immutable style like:
orders.mapIndexed { i, order ->
"data$i" to mapOf(
"id" to order.id,
"productName" to order.productName,
"quantity" to order.quantity
)
}.toMap()
You are creating the Map object outside the loop.
val map = HashMap()
So it will create single map entry where as you need different map for parent map.
Now you are entering different values in your map but since all maps references are now pointing to same Map Object so all Maps in your parent map will be showing last entries made to map.
The Solution is to keep val map = Hashmap() inside the loop. So with each iteration a different map objects will be created containg different data as per the iterations.
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);
Im using hashmap and arraylist...
How to sort the arraylist ? eg) In hashmap values are in order like one,two,three,four,five
but i stored these values in arraylist the order changed like three,one,five,two,four
In my code groupList,gnamelist and newList are all arraylist...
In print sts PLACES are in correct order but while print on NEWLIST PLACES the order changed
How to sort this in order?
My code
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PLACE, gname);
map.put(TAG_HOTEL,lname);
// adding HashList to ArrayList
groupList.add(map);
gnamelist.add(gname);
System.out.println("PLACES" + gnamelist);
List<String> newList = new ArrayList<String>(new LinkedHashSet<String>(gnamelist));
Collections.sort(newList,Collections.reverseOrder());
System.out.println("NEWLIST PLACES" + newList);
HashSet will store elements in an unordered fashion, and is likely the culprit of your element reordering.
List<String> newList = new ArrayList<String>(new HashSet<String>(gnamelist));
Also consider using LinkedHashMap/LinkedHashSet, which preserves the ordering of elements added to it.
Alternatively try the following:
gnamelist.add(gname);
System.out.println("PLACES" + gnamelist);
List<String> newList = new ArrayList<String>();
newList.addAll(gnamelist);
Try
Collections.sort(newList);
Edit:
If you want to sort in reverse use this
Collections.sort(newList,Collections.reverseOrder());
Important:
if you want to preserve insertion order, you need to use TreeSet instead of HashSet as HashSet doesn't preserve insertion order