Why is my loop not retrieving the last items? - java

I am trying to implement a method to view a list of items and their quantities, without being repeated. I am doing this using ArrayList which will hold objects of the type Item which I created. The Problem is in the loop where I remove duplicates from the a copy of the original list as it doesn't show the last two Items in the list and I don't know how to fix it. Here is the code. Item is very simple object, it contains (int identifier, int price, String name)
private ArrayList list;
public void print(ListOfItems storeList)
{
list = storeList.getList();
if ( list.size() == 0)
System.out.println("Sorry! There are no available Items at the store at this moment.");
/** I changed this section
else
{
Object[] originalItems = list.toArray();
ArrayList copy = storeList.getCopy(storeList.getList());
Object[] copyItems = copy.toArray();
System.out.println("Here is a list Of available items in this Store");
System.out.println("Name\tIdentifier\tprice\tQuantity");
//this loop is wrong
for (int i = 0; i < originalItems.length-1; i++)
{
for (int j = i+1; j < originalItems.length; j++)
{
if (originalItems[i].equals(originalItems[j]) && copyItems[j] != null)
{
copy.remove(originalItems[j]);
}
}
}
**/
//Below is the write loop
else
{
Object[] originalItems = list.toArray();
ArrayList copy = new ArrayList(list.size());
for (int i = 0; i < originalItems.length; i++)
{
Item item = (Item) originalItems[i];
if (copy.contains(item) == false)
{
copy.add(item);
}
}
Object[]cop = copy.toArray();
for (int i = 0; i < cop.length; i++)
{
if (cop[i] != null)
{
Item item = (Item) copyItems[i];
System.out.print(item.getName() + "\t");
System.out.print(item.getIdentifier() + "\t\t");
System.out.print(item.getPrice() + "\t");
System.out.print(Methods.getOccurences(list, item));
System.out.println();
}
}
System.out.print("*****************************");
}
}
Here is the class for ListOfItems
import java.util.ArrayList;
public class ListOfItems
{
int numOfItemsInStore = 50;
private ArrayList list = new ArrayList(numOfItemsInStore);
public ListOfItems()
{
Item item1 = new Item (111, 50, "Item1");
list.add(item1);
Item item2 = new Item (222, 99, "Item2");
list.add(item2);
Item item3 = new Item (333, 20, "Item3");
list.add(item3);
Item item4 = new Item (444, 199, "Item4");
list.add(item4);
Item item5 = new Item (555, 14, "Item5");
list.add(item5);
Item item6 = new Item (666, 40, "Item6");
list.add(item6);
list.add(item6);
list.add(item6);
list.add(item2);
list.add(item3);
list.add(item3);
list.add(item3);
}
public ArrayList getList()
{
return list;
}
public ArrayList getCopy(ArrayList listToCopy)
{
ArrayList copy = new ArrayList(numOfItemsInStore);
if (listToCopy.isEmpty())
System.out.println("This list is Empty");
else
{
Object[] listArray = listToCopy.toArray();
for (int i = 0; i < listArray.length; i++)
{
Item item = (Item) listArray[i];
copy.add(item);
}
}
return copy;
}
}
here is the Item class
public class Item
{
private int identifier;
private int price;
private String name;
public Item (int id, int price , String name)
{
this.identifier = id;
this.name = name;
this.price = price;
}
public int getIdentifier()
{
return identifier;
}
public int getPrice()
{
return price;
}
public String getName()
{
return name;
}
}

Okay first of all I would suggest to use a Set to remove duplicates...
public void print(ListOfItems storeList)
{
// At this point make sure that "getCopy(ArrayList <Item> listToCopy)" creates a deep copy!
ArrayList <Item> copyOfList = storeList.getCopy(storeList.getList());
// For using this statement make sure that you override "equals" in the "Item" class!
Set <Item> uniqueItems = new HashSet <Item> (copyOfList);
for(Item item : uniqueItems)
{
// Code for usage of each single item
}
}
...This is just one possible approach of solution, but makes sure that you overrides equals and that your function getCopy() creates a deep copy!
Thanks to Coderino Javarino, of course you must override the equals and the hashCode method not the toString method!
One option to override the equals method...
#Override public boolean equals(Object object)
{
if(this == object)
{
return true;
}
if(object == null || getClass() != object.getClass())
{
return false;
}
Item item = (Item) object;
return Objects.equals(this.name, item.name) &&
this.identifier == item.identifier &&
this.price == item.price;
}
And here an option to create a deep copy...
public ArrayList getCopy(ArrayList <Item> listToCopy)
{
if(null == listToCopy)
{
// Handle this option too
}
ArrayList <Item> copy = new ArrayList(listToCopy.size());
for(Item item : listToCopy)
{
// It is important that your class "Item" contains a copy constructor
copy.add(new Item(item));
}
return copy;
}

According to your code, I guess item 6 and item 3 were missed from your final cop list. Because remove action is not correct.
At the begin for-loop, the initial state of 3 variables are:
originalItems: [1,2,3,4,5,6,6,6,2,3,3,3]
copy: [1,2,3,4,5,6,6,6,2,3,3,3]
copyItems: [1,2,3,4,5,6,6,6,2,3,3,3]
The state of 3 variables above after outter for-loop finished round 6 (i=5):
originalItems: [1,2,3,4,5,6,6,6,2,3,3,3]
copy: [1,2,3,4,5,6,2,3,3,3] <- two item 6 were removed, it worked as expect
copyItems: [1,2,3,4,5,6,6,6,2,3,3,3]
Unluckily, when i=6 and j=7, we found that "item 6" is duplicate again, and the copy list removed it. <- the problem is here.
We are absolutely able to explain why "item 3" lost with the same idea. It happened when i=10, j=11.
And how to fix it? If you still want to use 2 for-loop, you can implement the strategy below:
init copy list is empty
init originalitem as copy of your list
for item in originalItem
isExist = false
for copy list
if item in copy
isExist = true
break
if isExist = false
copy add item
But, there are many ways to remove effectively a duplicate element in a list, rather than using 2 for-loop strategy.

else
{
Object[] originalItems = list.toArray();
ArrayList copy = new ArrayList(list.size());
for (int i = 0; i < originalItems.length; i++)
{
Item item = (Item) originalItems[i];
if (copy.contains(item) == false)
{
copy.add(item);
}
}

Related

Why am I getting wrong 0 index of value?

I am trying to learn how to add dynamically data into a list but I am facing a problem.
Why am I getting wrong value index of 0. when ever I trying to add a value position of index.
import java.util.*;
public class MyList{
String[] mList = null;
int pointer;
public MyList(){
mList = new String[pointer];
}
public void add(String aStringValue){
System.out.println("add: "+pointer+ " " +aStringValue+ " "+mList.length);
if (pointer < mList.length-1) {
System.out.println(pointer+ " " +aStringValue);
mList[pointer] = aStringValue;
pointer++;
}else{
System.out.println("New List:");
String[] lStringList = new String[mList.length + 20];
System.arraycopy(mList, 0, lStringList, 0, mList.length);
mList = lStringList;
System.out.println("New List: "+mList.length);
}
}
public int size(){
int size = 0;
for (int i = 0;i<mList.length;i++) {
if (mList[i] == null) {
return size;
}else{
size++;
}
}
return size;
}
public String get(int index){
return mList[index];
}
}
public class ListSize{
public static void main(String[] args){
MyList lList = new MyList();
lList.add("Amit");
lList.add("Deepak");
lList.add("Vishal");
lList.add("hello");
lList.add("abc");
lList.add("rahul");
lList.add("ajit");
lList.add("durgesh");
lList.add("a");
lList.add("b");
lList.add("c");
lList.add("d");
lList.add("e");
System.out.println("MyList is: "+lList.size());
for (int i = 0; i<lList.size(); i++) {
System.out.println(lList.get(i));
}
}
}
I expect the Output of Amit, Deepak but the Actual output is Deepak, vishal
When you create a new array, you don't add anything to it. I suggest you always check the size is ok, and afterwards, always add the element. If you want to see this clearly, I suggest stepping through the code in your debugger.
public void add(String aStringValue) {
// ensure capacity.
if (pointer == mList.length)
mList = Arrays.copyOf(mList, mList.length + 20);
mList[pointer++] = aStringValue;
}
In your add method, if the array hasn’t got room for the string you want to add, you are creating a new and bigger array, but not adding the string to the new array.
I believe that the code in the if part of your if statement should go after the if statement instead.

Sort ArrayList items by name

I am trying to rearrange an ArrayList based on the name of the items to be on specific index.
My list currently is this:
"SL"
"TA"
"VP"
"SP"
"PR"
and i want to rearrange them to:
"SL"
"SP"
"TA"
"PR"
"VP"
but based on the name and not in the index.
I have tried this:
for (int i=0; i< list.size(); i++){
if (list.get(i).getCategoryName().equals("SL")){
orderedDummyJSONModelList.add(list.get(i));
}
}
for (int i=0; i< list.size(); i++){
if (list.get(i).getCategoryName().equals("SP")){
orderedDummyJSONModelList.add(list.get(i));
}
}
for (int i=0; i< list.size(); i++){
if (list.get(i).getCategoryName().equals("TA")){
orderedDummyJSONModelList.add(list.get(i));
}
}
for (int i=0; i< list.size(); i++){
if (list.get(i).getCategoryName().equals("PR")){
orderedDummyJSONModelList.add(list.get(i));
}
}
for (int i=0; i< list.size(); i++){
if (list.get(i).getCategoryName().equals("VP")){
orderedDummyJSONModelList.add(list.get(i));
}
}
and it works fine, but i want to know if there is a more efficient way to do in 1 for loop or maybe a function. I do not wish to do it like this:
orderedDummyJSONModelList.add(list.get(0));
orderedDummyJSONModelList.add(list.get(3));
orderedDummyJSONModelList.add(list.get(1));
orderedDummyJSONModelList.add(list.get(4));
orderedDummyJSONModelList.add(list.get(2));
Which also works. Any ideas?
You can use Collection.Sort method as Collection.Sort(list) since list is a List<String> you will be fine. But if you want to implement a new comparator:
Collections.sort(list, new NameComparator());
class NameComparator implements Comparator<String> { //You can use classes
#Override
public int compare(String a, String b) { //You can use classes
return a.compareTo(b);
}
}
EDIT:
You can define a class comparator for your needs:
class ClassComparator implements Comparator<YourClass> { //You can use classes
#Override
public int compare(YourClass a, YourClass b) { //You can use classes
return a.name.compareTo(b.name);
}
}
The key thing here is: you need to get clear on your requirements.
In other words: of course one can shuffle around objects stored within a list. But: probably you want to do that programmatically.
In other words: the correct approach is to use the built-in Collection sorting mechanisms, but with providing a custom Comparator.
Meaning: you better find an algorithm that defines how to come from
"SL"
"TA"
"VP"
"SP"
"PR"
to
"SL"
"SP"
"TA"
"PR"
"VP"
That algorithm should go into your comparator implementation!
The point is: you have some List<X> in the first place. And X objects provide some sort of method to retrieve those strings you are showing here. Thus you have to create a Comparator<X> that works on X values; and uses some mean to get to those string values; and based on that you decide if X1 is <, = or > than some X2 object!
here´s an answer just specific for your problem working just for the given output. If the List contains anything else this might break your ordering, as there is no rule given on how to order it and the PR just randomly appears in the end.
public static void main(String[] args) {
List<String> justSomeNoRuleOrderingWithARandomPRInside = new ArrayList<String>();
justSomeNoRuleOrderingWithARandomPRInside.add("SL");
justSomeNoRuleOrderingWithARandomPRInside.add("TA");
justSomeNoRuleOrderingWithARandomPRInside.add("VP");
justSomeNoRuleOrderingWithARandomPRInside.add("SP");
justSomeNoRuleOrderingWithARandomPRInside.add("PR");
java.util.Collections.sort(justSomeNoRuleOrderingWithARandomPRInside, new NameComparator());
for(String s : justSomeNoRuleOrderingWithARandomPRInside) {
System.out.println(s);
}
}
static class NameComparator implements Comparator<String> { //You can use classes
#Override
public int compare(String a, String b) { //You can use classes
// Lets just add a T in front to make the VP appear at the end
// after TA, because why not
if (a.equals("PR")) {
a = "T"+a;
} else if(b.equals("PR")) {
b = "T"+b;
}
return a.compareTo(b);
}
}
O/P
SL
SP
TA
PR
VP
But honestly, this solution is crap, and without any clear rule on how to order these this will be doomed to fail as soon as you change anything as #GhostCat tried to explain.
How about this
// define the order
List<String> ORDER = Arrays.asList("SL", "SP", "TA", "PR", "VP");
List<MyObject> list = ...
list.sort((a, b) -> {
// lamba syntax for a Comparator<MyObject>
return Integer.compare(ORDER.indexOf(a.getString()), ORDER.indexOf(b.getString());
});
Note that this will put any strings that aren't defined in the ORDER list at the start of the sorted list. This may or may not be acceptable - it may be worth checking that only valid strings (i.e. members of ORDER) appear as the result of MyObject.getString().
Use a hashmap to store the weight of all strings (Higher the value of the hashmap means the later this string should come in the final list).
Using a Hashmap, so you can expand it later for other strings as well. It'll be easier to enhance in future.
Finally, Use a custom Comparator to do it.
Required Setup:
List<String> listOfStrings = Arrays.asList("SL", "TA", "VP", "SP", "PR");
HashMap<String, Integer> sortOrder = new HashMap<>();
sortOrder.put("SL", 0);
sortOrder.put("TA", 1);
sortOrder.put("VP", 2);
sortOrder.put("SP", 3);
sortOrder.put("PR", 4);
Streams:
List<String> sortedList = listOfStrings.stream().sorted((a, b) -> {
return Integer.compare(sortOrder.get(a), sortOrder.get(b));
}).collect(Collectors.toList());
System.out.println(sortedList);
Non-Stream:
Collections.sort(listOfStrings, (a, b) -> {
return Integer.compare(sortOrder.get(a), sortOrder.get(b));
});
OR
listOfStrings.sort((a, b) -> {
return Integer.compare(sortOrder.get(a), sortOrder.get(b));
});
System.out.println(listOfStrings);
Output:
[SL, TA, VP, SP, PR]
You can build an index map using a LinkedHashMap. This will be used to lookup the order which to sort using the category names of your items.
ItemSorting
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class ItemSorting {
public static void main(String[] args) {
List<Item> list = new ArrayList<Item>();
IndexMap indexMap = new IndexMap("SL", "SP", "TA", "PR", "VP");
ItemComparator itemComparator = new ItemComparator(indexMap);
list.add(new Item("SL"));
list.add(new Item("TA"));
list.add(new Item("VP"));
list.add(new Item("SP"));
list.add(new Item("PR"));
Collections.sort(list, itemComparator);
for (Item item : list) {
System.out.println(item);
}
}
}
ItemComparator
import java.util.Comparator;
public class ItemComparator implements Comparator<Item> {
private IndexMap indexMap;
public IndexMap getIndexMap() {
return indexMap;
}
public void setIndexMap(IndexMap indexMap) {
this.indexMap = indexMap;
}
public ItemComparator(IndexMap indexMap) {
this.indexMap = indexMap;
}
#Override
public int compare(Item itemA, Item itemB) {
if (itemB == null) return -1;
if (itemA == null) return 1;
if (itemA.equals(itemB)) return 0;
Integer valA = indexMap.get(itemA.getCategoryName());
Integer valB = indexMap.get(itemB.getCategoryName());
if (valB == null) return -1;
if (valA == null) return 1;
return valA.compareTo(valB);
}
}
IndexMap
import java.util.LinkedHashMap;
public class IndexMap extends LinkedHashMap<String, Integer> {
private static final long serialVersionUID = 7891095847767899453L;
public IndexMap(String... indicies) {
super();
if (indicies != null) {
for (int i = 0; i < indicies.length; i++) {
this.put(indicies[i], new Integer(i));
}
}
}
}
Item
public class Item {
private String categoryName;
public Item(String categoryName) {
super();
this.categoryName = categoryName;
}
public String getCategoryName() {
return categoryName;
}
public void setCategoryName(String categoryName) {
this.categoryName = categoryName;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((categoryName == null) ? 0 : categoryName.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
Item other = (Item) obj;
if (categoryName == null) {
if (other.categoryName != null) return false;
} else if (!categoryName.equals(other.categoryName)) return false;
return true;
}
#Override
public String toString() {
return String.format("Item { \"categoryName\" : \"%s\" }", categoryName);
}
}
Result
Item { "categoryName" : "SL" }
Item { "categoryName" : "SP" }
Item { "categoryName" : "TA" }
Item { "categoryName" : "PR" }
Item { "categoryName" : "VP" }
You coud define a helper method like this one:
public static int get(String name) {
switch (name) {
case "SL":
return 1;
case "SP":
return 2;
case "TA":
return 3;
case "PR":
return 4;
case "VP":
return 5;
default:
return 6;
}
}
and write in your main method something like:
ArrayList<String> al = new ArrayList<>();
al.add("SL");
al.add("TA");
al.add("VP");
al.add("SP");
al.add("PR");
Collections.sort(al, (o1, o2) -> return get(o1) - get(o2); );
al.forEach((s) -> System.out.println(s));
You can create a Map that maintains the position. When you iterate through the unordered list just get the position of that string value and insert into new array(not arraylist), then later if required you can convert that array to ArrayList.
Example code:
Map<String,Integer> map = new HashMap<>(); //you can may be loop through and make this map
map.put("SL", 0);
map.put("SP", 1);
map.put("TA",2);
map.put("PR",3);
map.put("VP",3);
List<String> list1 // your unordered list with values in random order
String[] newArr = new String[list1.size()];
for(String strName: list1){
int position = map.get(strName);
arr[position] = strName;
}
//newArr has ordered result.

How to get index from Arraylist which contains string

Below is my model:
public class Products {
String date = "", item = "";
public Products () {
}
public Products (String date String item ) {
this.date = date
this.item = item ;
}
public String getdate() {
return date
}
public void setdate (String date) {
this.date = date
}
public String getitem () {
return item
}
public void setitem (String item) {
this.item = item
}
}
And below code for defined the Arralist:
private ArrayList<TasksCharts> mArrayList;
and i have data in ArrayList:
position 0 -> date - "2016-10-02" , item = "pens"
position 1 -> date - "2016-10-03" , item = "xyz"
position 2 -> date - "2016-10-03" , item = "fts"
Now i want the position of ArraList whose contain "pens" . So for that i have eritten below code:
if (containsSubString(mArrayList, "pens")) {
int listIndex = getItemPos("pens");
}
private int getItemPos(String item) {
return mArrayList.indexOf(item);
}
When i runt this it will give me -1 index for item pens.
How can i get the index of particular item ?
Does a TasksCharts Object containing pens equal a String Object containing pens?
Unless you have overriden the equals method I would say "no".
I would recommend that you use a Map instead or you will have to loop through looking for a TasksCharts Object containing pens
You can run a for loop to get job done .
private int getItempos(ArrayList<TasksCharts> mArrayList, String str)
{
for(int i=0;i<mArrayList.size();i++)
{
if(mArrayList.get(i).item.indexOf(str)!=-1)
{
return i;
}
}
return -1;
}
Hope this helps!
you should do sth like this :
private int getItemPos(String key , String item) {
int i = 0;
for (i=0; i<mArrayList.size(); i++)
{
if(mArrayList.get(i).get(key).equalsIgnoreCase(item))
{
return i;
}
}
return -1;
}
and call
int x = getItemPos("item" , "pen");
I have simply added products in the same ArrayList and then used for-loop to find that product position.
ArrayList<Products> mArrayList = new ArrayList<>();
Products products1 = new Products("2016-10-05", "Pens");
Products products2 = new Products("2016-10-04", "Pencil");
Products products3 = new Products("2016-10-03", "Book");
Products products4 = new Products("2016-10-02", "Dairy");
mArrayList.add(products1);
mArrayList.add(products2);
mArrayList.add(products3);
mArrayList.add(products4);
for (Products products : mArrayList) {
if (products.getitem().equals("Pens")) {
Log.d("Position", mArrayList.indexOf(products) + "");
}
}
This will give Output as
D/Position: 0

Data modifies automatically in ArrayList

I have two ArrayLists:
private ArrayList<MenuItemBean> newList= new ArrayList<MenuItemBean>();
private ArrayList<MenuItemBean> newGroupList= new ArrayList<MenuItemBean>();
In one function I am adding data to one ArrayList:
public void setConfirmList(List<MenuItemBean> cList){
newList.addAll(cList);
listAdapter=new ListAdapter(context, newList);
lv_item.setAdapter(listAdapter);
}
Another function where I am just grouping data (increasing quantity if product is already exist) using for-loop and adding data to a second ArrayList. But my problem is as I increase quantity in ArrayList2, my quantity in ArrayList1 itself modifies. I know its because of same reference of objects. Can we change this behavior by any way.
private void groupList() {
newGroupList.clear();
ArrayList<MenuItemBean> mList= new ArrayList<MenuItemBean>();
mList.addAll(newList);
for (int i = 0; i < mList.size(); i++){
String productId = mList.get(i).getProductId();
if(newGroupList.size()==0){
newGroupList.add(mList.get(i));
}else{
Boolean bool=false;
for (int j = 0; j< newGroupList.size(); j++){
if(productId.equalsIgnoreCase(newGroupList.get(j).getProductId())){
bool= true;
// MenuItemBean newObject = new MenuItemBean();
// BeanUtils.copyProperties(newObject, newGroupList.get(j));
MenuItemBean bean= newGroupList.get(j);
int quantity = Integer.parseInt(bean.getUserQuantity());
Double sellingPrice = Double.parseDouble(bean.getSellingPrice());
quantity = quantity + 1;
sellingPrice = sellingPrice * quantity;
bean.setUserQuantity(String.valueOf(quantity));
bean.setUserPrice(String.valueOf(sellingPrice));
newGroupList.set(j, bean);
break;
}
}
if(!bool){
newGroupList.add(mList.get(i));
}
}
}
listAdapter=new ListAdapter(context, newGroupList);
lv_item.setAdapter(listAdapter);
}
I also tried by making copy of ArrayList by using
ArrayList newGroupList= new ArrayList<MenuItem>(newList);
But no help it simple copies data but not the reference. I tried but do not get any example to implement this.
But no help it simple copies data but not the reference.
You're right. By create new list and add data item to new list it's not copy object memory. Both item in those list point to same memory address in heap. So when you modify data item in one of those list. This affects others data item too. for example
public static void main(String[] args) {
List<ObjectItem> datas = new ArrayList<ObjectItem>();
ObjectItem obj1 = new ObjectItem();
obj1.setId(1);
datas.add(obj1);
System.out.println("memory addrs for obj1:" + datas.get(0)); //memory addrs for obj1: 533e846f
List<ObjectItem> other_datas = new ArrayList<ObjectItem>();
other_datas.addAll(datas);
System.out.println("memory addrs for obj1:" + other_datas.get(0));//memory addrs for obj1: 533e846f
}
If you want to solve your problem, let's make deep copy data. For example:
public class ObjectItem {
public ObjectItem(ObjectItem other) {
this.id = other.getId();
}
private int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
And then using it
List<ObjectItem> new_datas = new ArrayList<ObjectItem>();
for (int i = 0; i < datas.size(); i++) {
new_datas.add(new ObjectItem(datas.get(i)));
}

how to compare two arraylist<Contacts> in java

I am comparing two arraylist (Contacts .java is an pojo class). First Arraylist contains some Items and second arraylist contains some Items. By comparing two list, if both list contains same element it should not be added and else added to first list. But I cannot do it. Below is my code. Help will be appreciated.
public void insertmanualandxmldata()
{
mContacts = storage.getarraylist(); // Arraylist
if(mContacts != null)
{
for(int i=0; i<mContacts.size(); i++)
{
ContactVO mShareddata = mContacts.get(i);
//mParsedDataSetList arraylist
for(int j=0; j<mParsedDataSetList.size(); j++)
{
ContactVO mXmldata = mParsedDataSetList.get(j);
if(mShareddata.getNumber().contains(mXmldata.getNumber()))
{
mContacts.add(mXmldata);
}
}
}
storage.savearraylist(mContacts);
}
else
{
storage.savearraylist(mParsedDataSetList);
}
}
Implement Comparable
private class ContactsVO implements Comparable<ContactsVO>{
int number;
#Override
public int compareTo(ContactsVO that)
{
if (this.number> that.number)
return 1;
else if (this.number< that.number)
return -1;
else
return 0;
}
}
And your logic.. Add contents of list 2 to list 1. while adding we have to compare if list 1 already has that item.
for(int j=0; j < mParsedDataSetList.size(); j++)
{
ContactVO mXmldata = mParsedDataSetList.get(j);
boolean exists = false;
for(int i=0; i< mContacts.size(); i++)
{
ContactVO mShareddata = mContacts.get(i);
if(mShareddata.comprareTo(mXmldata) == 0)
{
exists = true;
break;
}
}
if(!exists)
{
mContacts.add(mXmldata);
}
}
You could implement a class that extends ArrayList and create a Comparator like this:
public static Comparator<T> Comp = new Comparator<T>(){
public int compare(Type e1, Type e2){
return (e1.getSomething().compareTo(e2.getSomething()));
}
};
If you have never used comparators before here is a good tutorial https://docs.oracle.com/javase/tutorial/collections/interfaces/order.html
What comparators basically do is to provide a criteria for comparing elements.
There are two approaches by implementing comparator or comparable.
For your requirement I would suggest you can implements Comparable in your ContactVO class. And override compareTo method.
private class ContactsVO implements Comparable<ContactsVO> {
private Integer number;
// Remaining attributes and their getter setter.
public Integer getNumber() {
return number;
}
public void setNumber(Integer number) {
this.number = number;
}
#Override
public int compareTo(ContactsVO compareWith) {
if (this.getNumber() > compareWith.getNumber())
return 1;
else if (this.getNumber() < compareWith.getNumber())
return -1;
else
return 0;
}
}
If comparing attribute (in our case is number) implements Comparable then we can rewrite compareTo method as
#Override
public int compareTo(ContactsVO compareWith) {
return this.getNumber().compareTo(compareWith.getNumber());
}
Note: Some basic data types such as Integer, String implements Comparable.
Here contactList1 and contactList2 is your two list of POJO class Contacts
Set<Contacts> contactList3 = new HashSet<Contacts>(contactList1);
contactList3.addAll(contactList2);
ArrayList<Contacts> newList = new ArrayList<Contacts>(contactList3);
System.out.println("New List :"+newList);
Try to use LinkedHashSet which will not allow duplicates :
ArrayList arrayList1 = new ArrayList();
ArrayList arrayList2 = new ArrayList();
ArrayList arrayList3 = new ArrayList();
arrayList3.addAll(arrayList1);
arrayList3.addAll(arrayList2);
HashSet hashSet = new HashSet();
hashSet.addAll(arrayList3);
arrayList3.clear();
arrayList3.addAll(hashSet);
Note : when you required to maintain ordering of you list item use LinkedHashSet instead of HashSet.

Categories

Resources