Duplicate keys in LinkedHashMap - android

Suppose I have LinkedhashMap<String, List> myLHM = new LinkedHashMap<>()
Values of myLHM :
<Roy,[1,2,3]>
<Roy,[14,15,16]>
<Neha,[1,5,6]>
<Neha,[11,12,13]>
<Jane,[11,8,9]>
In above eg., Roy and Neha is repetitive/duplicate.
Is it possible to hold duplicate keys in myLHM ? Because I'm not able to store duplicate keys
No? Then what is the alternative to LinkedHashMap to hold duplicate keys?
TIA!
Edit: Those two Roy and Neha are each the same person

I don't know of any map in the standard java library that can hold duplicate keys, but Guava is an excellent extension to the normal java Collections (and more) done by Google. There you have Multimap which can hold several values for the same key (I guess this is what you want in the end). The main benefit I find in using such a library/implementation is that it will take care of everything for you associated with the storage of the values and you don't need to bother about implementing it yourself.
PS: Guava is not just about Collections, which I think it's another Pro why you should check it out.

Add a List of items by key. Whenever you insert, if key was found, just add to the collection. When not found, add a new colelction with current item.

I solved this by myself.
What I did is used :
LinkedHashMap<String, ArrayList<ArrayList>> myLHM = new LinkedHashMap<>() ;
Inserted into it as:
ArrayList<ArrayList> multiDimArray = new ArrayList<>();
ArrayList list = new ArrayList();
list.add("abc");//some string 1
list.add("lmn");//some string 2
list.add("xyz");//some string 3
multiDimArray.add(list);
myLHM.put("abc"/*use your variable OR pass value like myList.get(position)*/,multiDimArray);
Fetched / Retrieved values as:
List tempNames=new ArrayList();
Iterator myVeryOwnIterator = myLHM.keySet().iterator();
while(myVeryOwnIterator.hasNext()) {
tempNames.add(myVeryOwnIterator.next());
}
ArrayList<ArrayList> tempArrayList = new ArrayList();
for (int i=0;i<tempNames.size();i++){
tempArrayList.addAll(myLHM.get(tempNames.get(i)));
}
String item = null; int year = 0; int amount = 0;
for (int i=0;i<tempArrayList.size();i++) {
for (int j=0;j<tempArrayList.get(i).size();j++){
if(j==0){
item = (String) tempArrayList.get(i).get(j);
item = item.replaceAll("\\s", "_");
} else if (j==1){
year = Integer.valueOf(tempArrayList.get(i).get(j).toString());
} else if (j==2){
amount = Integer.valueOf(tempArrayList.get(i).get(j).toString());
} else {
Log.e("Problem","for loop error");
}
}
db.execSQL("INSERT INTO ch // my insert query...
VALUES(" +"'" + item +"'," + year +"," + amount +"," + id +");");
}

Related

How to separate until last element of ArrayList in android

I need to assign an ArrayList's data into a String variable.
Using following code I am getting tempSeats equals jack, ravi, mike,
ArrayList<String> userSelectedSeats = new ArrayList<String>();
userSelectedSeats.add("jack");
userSelectedSeats.add("ravi");
userSelectedSeats.add("mike");
for (String s : userSelectedSeats) {
tempSeats += s + ", ";
}
but output should be jack, ravi, mike What modification should I do to my code?
Let Java's streams do the heavy lifting for you:
String tempSeats = userSelectedSeats.stream().collect(Collectors.joining(", "));
You're adding a comma after the end of every item, even the last item. You only want to add a comma if the item isn't the last item in the list. This is called joining.
If you're using Java 8, you can do
userSelectedSeats.stream().collect(Collectors.joining(", "))
Otherwise see this question for further info.
A simple String.join will accomplish the task at hand.
String result = String.join(", ", userSelectedSeats);
Replace the for loop with this,
tempSeats = TextUtils.join(", ",userSelectedSeats);
Hope it helps!
String c;
ArrayList<String> userSelectedSeats = new ArrayList<String>();
userSelectedSeats.add("jack");
userSelectedSeats.add("ravi");
userSelectedSeats.add("mike");
for (int i=0; i < userSelectSeats.length(); i++)
c += userSelectSeats.get(i).toString()+ ",";

To remove key from hashmap and rearrange keys when used in recycler view

Please any one can help how to remove particular key from hashmap and then rearrange the keys in hashmap accordingly.
Below is my code.
Set<Integer> integerSet = hashMap.keySet();
int removekey = pos;
ArrayList<Integer> integers = new ArrayList<>();
for (Integer integer : integerSet) {
if (integer > removekey) {
integers.add(integer);
}
}
for (Integer integer : integers) {
if (hashMap.containsKey(integer)) {
AddCardPojo pojo = hashMap.get(integer);
pojo.setImagCard(cardImage[integer - 1]);
hashMap.remove(integer);
hashMap.put(integer - 1, pojo);
}
}[![enter image description here][1]][1]
I have attached screenshot of error
You can directly remove a key value pair,you can directly do
hashMap.remove(removeKey);
as for 're arranging keys in hashmap',
it is a data structure which makes no guarantees of order of data.
Check this answer for more
If you need a particular order as per integer, you could use arraylist
Finally it could be done.
Below is my answer.
hashMap.remove(key);
List<AddCardPojo> hashMapsList=new ArrayList<>();
Iterator it = hashMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
hashMapsList.add((AddCardPojo) pair.getValue());
}
hashMap = new HashMap<>();
for(int i=0; i<hashMapsList.size();i++){
hashMap.put(i,hashMapsList.get(i));
}

Dynamic Adding item to list with different list and different adapter

how can I add item to list adapter, but every time I iterate n, it will add to a different list and different adapter, thanks!
//my first code
int n = 1;
while (n != 16) {
Day(n, Fullname);
n +=1 ;
}
//the other one that will add to the list and adapter
private void Day(int n,String Fullname){
String Date = "0" + n + "-" + Month + "-" + Year;
Cursor c = db.GetSpecific(Fullname,Date);
String allowancecount = "";
int intallowancecount = 0;
double totalCom = 0;
while(c.moveToNext()){
String serviceprice = c.getString(4);
String serviceperformedbynumber = c.getString(10);
allowancecount = c.getString(12);
intallowancecount = intallowancecount + Integer.parseInt(allowancecount.trim());
double income = Integer.parseInt(serviceprice.trim())/
Integer.parseInt(serviceperformedbynumber.trim());
totalCom = totalCom + income ;
//here what to do?
String add ="List" + n + ".add(String.valueOf(" + income + "));";
do add;//???????
}
//here what to do?
String Dynamic = "Com" + n + ".setText(String.valueOf(" + totalCom + "))";
do Dynamic ;//?????????
String Dynamicadapter = "Lv" + n + ".setAdapter(adapter" + n + ")";
do Dynamicadapter ;//????????
}
i'm just thinking if this was possible, but if not, i'll do it on the other way i know,open for any suggestions, thanks again.
It isn't possible in Java to assign variable using a variable name. However, there are things that you can use for these types of situations which allow you to almost do this, but everything is created correctly at runtime without the need for dynamic behaviour. For example, you can think about this in terms of using an associative array.
Taken from Wikipedia -https://en.wikipedia.org/wiki/Comparison_of_programming_languages_(mapping)#Java
In Java associative arrays are implemented as "maps"; they are part of
the Java collections framework. Since J2SE 5.0 and the introduction of
generics into Java, collections can have a type specified; for
example, an associative array mapping strings to strings might be
specified
So in light of this, you could use a Map and restructure your code to do the following:
Create your adapter object
Set it's properties (such as setAdapter())
Add it to the map by using i (or whatever you want to use as a key for this)
Access it later on from the map using the key/dynamic 'variable name'
Map<Integer, ArrayAdapter<String>> map = new HashMap<Integer, ArrayAdapter<String>>();
for(int i = 0; i < 10; i++)
{
map.put(i, yourAdapter);
}

Why does my SparseArray return an ArrayList with zero elements?

I'm iterating through a cursor and populating a SparseArray with ArrayList's containing bundles of information from the cursor:
// An ArrayList to hold all of our components per section
ArrayList<ObjectKanjiLookupChar> al = new ArrayList<ObjectKanjiLookupChar>();
// We'll hold on to all of the above ArrayLists and process them at once
SparseArray<ArrayList<ObjectKanjiLookupChar>> compArray = new SparseArray<ArrayList<ObjectKanjiLookupChar>>();
do
{
// Read values from the cursor
int id = cursor.getInt(cursor.getColumnIndex("_id"));
String component = cursor.getString(cursor.getColumnIndex("component"));
int compStrokes = cursor.getInt(cursor.getColumnIndex("strokes"));
// Create a new object for this component so we can display it in the GridView via an adapter
ObjectKanjiLookupChar oklc = new ObjectKanjiLookupChar();
oklc.setCharacterID(id);
oklc.setCharacter(component);
oklc.setStrokeCount(compStrokes);
al.add(oklc);
// Add headers whenever we change stroke groups
if(compStrokes != strokesSection)
{
compArray.put(strokesSection, al);
al.clear();
strokesSection = compStrokes;
}
}
while(cursor.moveToNext());
// Add the final group of components to the array
compArray.put(strokesSection, al);
Immediately afterwards, I iterate through the SparseArray:
for(int i = 0; i < compArray.size(); i++)
{
Integer strokes = compArray.keyAt(i);
ArrayList<ObjectKanjiLookupChar> alComp = compArray.get(strokes);
// DEBUG
Log.i("DialogKanjiLookup", "Components in Section " + strokes + ": " + alComp.size());
ll.addView(createNewSection(String.valueOf(strokes), alComp));
}
For some unknown reason, the Log() call above reports that alComp has zero entries. I verified that ArrayList.size() was returning numbers greater than 0 when I put() them into the SparseArray, so I must be doing something incorrect when iterating through the SparseArray. What is going on?
I suspect that the problem comes from this piece of code:
if(compStrokes != strokesSection)
{
compArray.put(strokesSection, al);
al.clear(); // Here
strokesSection = compStrokes;
}
You cleared the array list after you added to the SparseArray. You might think that after you have added the list to the SparseArray, SparseArray would keep a copy of the ArrayList. However, they actually share the same reference. Since you cleared the ArrayList, you cleared out the one inside SparseArray too.
The following code should fix the problem.
// We'll hold on to all of the above ArrayLists and process them at once
SparseArray<ArrayList<ObjectKanjiLookupChar>> compArray = new SparseArray<ArrayList<ObjectKanjiLookupChar>>();
do
{
// Read values from the cursor
int id = cursor.getInt(cursor.getColumnIndex("_id"));
String component = cursor.getString(cursor.getColumnIndex("component"));
int compStrokes = cursor.getInt(cursor.getColumnIndex("strokes"));
// Create a new object for this component so we can display it in the GridView via an adapter
ObjectKanjiLookupChar oklc = new ObjectKanjiLookupChar();
oklc.setCharacterID(id);
oklc.setCharacter(component);
oklc.setStrokeCount(compStrokes);
ArrayList<ObjectKanjiLookupChar> al = compArray.get(comStrokes);
if(al == null) {
al = new ArrayList<ObjectKanjiLookupChar>();
compArray.put(comStrokes, al);
}
al.add(oklc);
}
while(cursor.moveToNext());

Populate listview according to distance

I am using gooleplaces API. I have a response in json, but the problem is I want to populate listview according to distance. I make the sorted distance arraylist in ascending order using collections.sort(), but how do I sort other lists based on this sorted list to populate my listview correctly?
If you are creating separate lists, then you need to your define method, and if you are using list of single collection, or data structure, you can define your comparator, then call sort on this, list.
Finally I resolve my problem using bubble sort.
if (distanceList.size()>1) // check if the number of orders is larger than 1
{
for (int i=0; i<distanceList.size()-1; i++) // bubble sort outer loop
{
for (int j=0; j < distanceList.size()-1-i; j++) {
if (distanceList.get(j)>(distanceList.get(j+1)) )
{
int temp = distanceList.get(j);
distanceList.set(j,distanceList.get(j+1) );
distanceList.set(j+1, temp);
String temp1 = nameList.get(j);
nameList.set(j,nameList.get(j+1) );
nameList.set(j+1, temp1);
String temp2 = vicinityList.get(j);
vicinityList.set(j,vicinityList.get(j+1) );
vicinityList.set(j+1, temp2);
String temp3 = latList.get(j);
latList.set(j,latList.get(j+1) );
latList.set(j+1, temp3);
String temp4 = longList.get(j);
longList.set(j,longList.get(j+1) );
longList.set(j+1, temp4);
}
}
}
}

Categories

Resources