I am having 2 arraylist , arraylist are field from web-service
I have to compare arraylist and find un-common value from both
Arraylist is dynamic and changing continious
What i have done is :
for (int i = 0; i < arraylist.size(); i++) {
for (int j = 0; j < arraylist1.size(); j++) {
if ((arraylist.get(i).get("alert_id")).equals(arraylist1.get(j).get("alert_id")))
{
Log.e("Same", "faltu");
}
else {
Log.e("not same", "not faltu");
}
}
}
value :
arraylist 1 = id=92
arraylist 2 =id1 92
arraylist 1 = id1=91
arraylist 2 =id1 91
arraylist 1 = id1=86
arraylist 2 =id1 86
arraylist 1 =id1=85
arraylist 2 =id1 85
arraylist 1 = id1=84
arraylist 2 =id1 84
arraylist 1 = id1=81
arraylist 2 =id1 81
arraylist 1 =id1=80
arraylist 2 =id1 80
arraylist 1 = id1=79
arraylist 2 =id1 79
First you had to loop the two arraylist and you had to check whether the values are equal (OR) not. If the values are not equal, then it has to be added in the separate list and before adding to the list make sure the last value it is checked till the last value in the inner loop. The below code describes the sample process,
ArrayList<String> unCommonList = new ArrayyList<String>();
for (int i= 0; i<arraylist.size();i++) {
for (int j= 0; j<arraylist1.size();j++) {
if (!arrayList.get(i).equal(arraylist1..get(j))) {
//Checking whether the last value in the list..
if (j == (arrayList1.Size() - 1)) {
unCommonList.add(arrayList.get(i));
}
}
}
}
/* Try this one */
ArrayList<Integer> arrayList=new ArrayList<>();
arrayList.add(1);
arrayList.add(2);
arrayList.add(3);
arrayList.add(4);
ArrayList<Integer> arrayListtwo=new ArrayList<>();
arrayListtwo.add(1);
arrayListtwo.add(3);
arrayListtwo.add(4);
arrayListtwo.add(6);
for(int i=0;i<arrayList.size();i++){
for(int j=0;i<arrayListtwo.size();j++){
if(arrayListtwo.get(j).equals(arrayList.get(i))){
Log.e("equal",""+arrayList.get(i));
}else{
Log.e("unequal",""+arrayList.get(i));
}
}
}
List<Integer> A1 = new ArrayList<Integer>();
A1.add(1);
A1.add(6);
A1.add(3);
A1.add(9);
List<Integer> B1 = new ArrayList<Integer>();
B1.add(3);
B1.add(6);
You should be better off calling remove(Object obj) with each element in the collection containing objects to be removed. This method removes the first instance of obj so if you want to remove all occurrences you will have to take care of that. If the object has been found and removed successfully it returns a true otherwise a false is returned.
Hope this is what you were looking for?
List<Integer> A1MinusB1 = new ArrayList<Integer>(A1);
A1MinusB1.removeAll(B1);
And the result will be
Results:
1
9
Or
You can do this.
// Make the two lists
List<Integer> list1 = Arrays.asList(1, 2, 3, 4);
List<Integer> list2 = Arrays.asList(2, 3, 4, 6, 7);
// Prepare a union
List<Integer> union = new ArrayList<Integer>(list1);
union.addAll(list2);
// Prepare an intersection
List<Integer> intersection = new ArrayList<Integer>(list1);
intersection.retainAll(list2);
// Subtract the intersection from the union
union.removeAll(intersection);
// Print the result
for (Integer n : union) {
System.out.println(n);
}
You can use HashMap.put() method.
If it returns any value means a key value pair already exists. If it returns null means no Key-Value pair exists.
This is most efficient way to find duplicates.
Related
I am offering products in the menuItemArrayList and as the user places products of their choice in the shopping cart, they will be added to the selectionItemArrayList. Here is my code that checks to see if the product already exists in the shopping cart. If so then only the quantity gets updated.
I have twiddling around with the code but I keep getting this error
IndexOutOfBoundsException: Index: 0, Size: 0
The code is just an extract from an onClickListener from the recyclerview's onBindHolder:
int position = getAdapterPosition();
for (int j = 0; j <= selectionItemArrayList.size(); j++) {
if (menuItemArrayList.get(position).getMenuItemName().equals(selectionItemArrayList.get(j).selectionName)) { // Loop through selection array to see if item exists in array
selectionItemArrayList.get(j).selectionQuantity += 1; // if it does exist then only update the quantity by 1
} else {
// Get the item name, price and add 1 to the quantity
String menuItemName = menuItemArrayList.get(position).getMenuItemName();
String menuItemPrice = menuItemArrayList.get(position).getMenuItemPrice();
SelectionItem selectionItems = new SelectionItem(menuItemName, menuItemPrice, 1);
selectionItemArrayList.add(selectionItems);
}
}
Any idea what I am doing wrong? The exception is thrown on the line where I compare the product name in the main array with the one in the cart array.
This is your loop:
for (int j = 0; j <= selectionItemArrayList.size(); j++)
When iterating over a list, you almost always want to use <, and not <=. This is because lists indices start from 0. So a list of size 2 has items at 0 and 1.
When you use <= on a list with zero elements, it will still try to access the element at index 0 (because 0 is <= 0). But your list is empty; it has no element at index 0. So you crash.
Try this instead:
for (int j = 0; j < selectionItemArrayList.size(); j++)
I have a JSONArray which contains many records. I want to compare a string inside those object with a similar(I know it has the same value) record in my SQLite db. but when I loop the table each row value has the first row value.
INSERT A RECORD TO DB >> it returns different value
ArrayList<String> fieldsNameTasse = new ArrayList<String>();
ArrayList<String> fieldsValueTasse= new ArrayList<String>();
for (int i = 0; i < pagamenti.length(); i++) {
JSONObject row = pagamenti.getJSONObject(i); /** LOOP OGGETTI */
String fattura = row.getString("Fattura");
String descrizione = row.getString("Descrizione");
String scadenza = row.getString("Data Scadenza");
String importo = row.getString("Importo");
String stato = row.getString("Stato Pagamento");
// FATURA SHOW ALL DIFFRERENtS VALUE CORRECTLY
fieldsNameTasse.add("fattura");
fieldsValueTasse.add(fattura);
Toast.makeText(getContext(), fattura.toString(), Toast.LENGTH_LONG).show();
fieldsNameTasse.add("descrizione");
fieldsValueTasse.add(descrizione);
fieldsNameTasse.add("scadenza");
fieldsValueTasse.add(scadenza);
fieldsNameTasse.add("importo");
fieldsValueTasse.add(importo);
fieldsNameTasse.add("stato");
fieldsValueTasse.add(stato);
DBmanager.insert("TasseIncoming", fieldsNameTasse, fieldsValueTasse);
}
CHECK DB ROW VALUE << it returns always the first value
/** SHOW ALWAYS THE SAME VALUE*/
int counter = 0;
Cursor cursor = DBmanager.readAll("TasseIncoming");
while(cursor.moveToNext()) {
String ffattura = cursor.getString(cursor.getColumnIndex("fattura"));
counter++;
Toast.makeText(getContext(), ffattura+" - "+counter, Toast.LENGTH_LONG).show();
}
ArrayList<String> fieldsNameTasse = new ArrayList<String>();
ArrayList<String> fieldsValueTasse= new ArrayList<String>();
for (int i = 0; i < pagamenti.length(); i++) {
// add stuff to the above arraylists
DBmanager.insert("TasseIncoming", fieldsNameTasse, fieldsValueTasse);
}
Every time you loop, you're just adding values to the end of what's already in those ArrayLists. So there's lots of duplicate column names with different values for each. Some quick testing:
sqlite> create table foo(a, b);
sqlite> insert into foo(a,b,a,b) values(1,2,3,4);
sqlite> select * from foo;
a b
---------- ----------
1 2
indicates that when a column is included multiple times in an INSERT, only the first corresponding value is used. Hence only ever getting the values from the first iteration of the loop.
The easy fix is to move those variable definitions inside the loop, so each insert is done with a fresh set of columns and values:
for (int i = 0; i < pagamenti.length(); i++) {
ArrayList<String> fieldsNameTasse = new ArrayList<String>();
ArrayList<String> fieldsValueTasse= new ArrayList<String>();
// add stuff to the above arraylists
DBmanager.insert("TasseIncoming", fieldsNameTasse, fieldsValueTasse);
}
I try to send several lists to other activity so I wrote the following code:
ArrayList<String> sections = new ArrayList<String>();
for(int i=1; i<=last; i++)
{
sections.clear();
for(j = 0; j < size; j++)
{
sections.add(someText);
}
ourIntent.putStringArrayListExtra("sections_"+i, sections);
}
As you can see for every loop cycle of i, the name I give to the sent list is different (sections_1, sections_2, ...).
The sections list is cleared in each loop cycle. And in debug mode I can see that in every loop cycle the sections have the right list.
The problem is in the next activity. When I take the list, with the following code:
sections1 = extras.getStringArrayList("sections_1");
sections2 = extras.getStringArrayList("sections_2");
sections1 and sections2 get the same list, which is the last list that was inserted in putStringArrayListExtra.
Anyone can explain this behavior?
I believe this is because it's storing a reference to your ArrayList, and not a copy of the current "state" of the list on each iteration of your loop.
For example, you first insert a reference to your ArrayList when it contains 1 item. Next, you insert a reference to your ArrayList when it contains 2 items. Both are just references, so when you actually transition to the next Activity, it copies the full ArrayList.
To fix this, you could actually make a local copy of the ArrayList each time you loop.
ArrayList<String> sections = new ArrayList<String>();
for(int i=1; i<=last; i++) {
sections.clear();
for(j = 0; j < size; j++){
sections.add(someText);
}
// Creating a new local copy of the current list.
ArrayList<String> newList = newArrayList<>(sections);
// Inserting the local copy instead.
ourIntent.putStringArrayListExtra("sections_"+i, newList);
}
I am trying to save some values in a arraylist but somehow they all get overwritten ending up with only 1 value in the arraylist (200).
final String[] titles = new String[urls.length];
for (int i = 0; i < titles.length; i++){
ArrayList<Integer> valuesList = new ArrayList<Integer>();
valuesList.add(page.getTopicCount()); // returns 4 values (50,100,150,200)
System.out.println("Element: " + valuesList.toString());
// returns only value 200
}
The code page.getTopicCount() returns the 4 values in 1 line (50 100 150 200) only the last one (200) gets added to the arraylist but i am trying to find a way to save them all 4 seperately.
What options do i have? (SharedPreferences, saving to file, do i have to build another loop)?
I already did some research and ended up on this page but i don`t know if this will work.
Ps: the 4 values are constantly changing, thus it is no option to add them as:
valuesList.add("50");
valuesList.add("100");
etc..
Edit:
getTopicCount is part of a Saxparser class, see below code snippet:
public void endElement(final String uri, final String localName, final String qName)
throws SAXException {
//
} else if (localName.equals("topiccount")) {
in_topiccount = true;
sb = new StringBuilder();
}
//
else if (localName.equals("topiccount")) {
in_topiccount = false;
forumPage.setTopicCount(Integer.parseInt(sb.toString())); //returns 50 100 150 200
sb = null;
}
//
}
Inside the for loop, you are initializing the valuesList ArrayList. So each iteration, you create a new ArrayList and add one element to it and then discard it. As a result, at the end you only have a reference to the last ArrayList you created, which can only have 200 in it.
Presumably what you want to do is something like:
ArrayList<Integer> valuesList = new ArrayList<Integer>();
for (int i = 0; i < titles.length; i++){
valuesList.add(page.getTopicCount()); // returns 4 values (50,100,150,200)
}
System.out.println("Element: " + valuesList.toString());
Edit: Essentially, create the ArrayList once, and then insert elements into it in the for loop.
I have list of integer IDs. Lets say this list is ArrayList<Integer> or int[], it doesn't matter. I have another ArrayList<Obj> that contains the objects with the same ids like in the first list, but they are ordered in different order.
I want to order the objects in the second list in the order as the ids in the first list.
EXAMPLE:
FIRST LIST: { 1, 5, 4, 8, 6 }
SECOND LIST: { Obj[id=5], Obj[id=8], Obj[id=6], Obj[id=1], Obj[id=4] }
RESULT LIST: { Obj[id=1], Obj[id=5], Obj[id=4], Obj[id=8], Obj[id=6] }
Can someone tell me an (efficient) way to do this?
I would suggest using a map:
Map<Integer, Obj> map = new HashMap<Integer, Obj>(secondList.size() * 2);
for (final Obj obj : secondList) {
map.put(obj.id, obj);
}
for (int i = 0; i < secondList.size(); i++) {
secondList.set(i, map.get(firstList.get(i)));
}
This runs in O(n), which IMHO is pretty much the best you can get.
A/ Create a matching id index list, such as:
1 -> 0
5 -> 1
4 -> 2
8 -> 3
6 -> 4
That's a reversed reference of your first list. It indicates the position of each id. A SparseIntArray is a good way of doing it:
SparseIntArray ref = new SparseIntArray();
for (int i = 0; i < firstList.size(); i++) {
ref.append(firstList.get(i), i);
}
Then you need to sort your second list using a Comparator that uses the id of the Object and the ref table:
Collections.sort(secondList, new Comparator<Obj>() {
public int compare(Obj t1, Obj t2) {
return ref.get(t1.id) - ref.get(t2.id);
}
});
I was in the middle of writing Etienne's answer when he posted it, so just for fun here's an O(N^2) solution with a smaller constant factor that doesn't create any objects:
int[] first = { 1, 5, 4, 8, 6 };
Obj[] second = { Obj[id=5], Obj[id=8], Obj[id=6], Obj[id=1], Obj[id=4] };
int i = 0;
while(i < second.length) {
int ind = -1;
for(int j=0;j<first.length;j+=1) {
if(first[j] == second[i].id) {
ind = j;
break;
}
}
if(ind == -1) break; //Bad news
if(ind == i) {
i += 1;
} else {
Obj temp = second[i];
second[i] = second[ind];
second[ind] = temp;
}
}
Obviously the creation of second[] is pseudocode, but the rest will work if the arrays are equal length. I think this will be a little bit faster than Etienne's for very small data sets, but you'd have to profile both answers.