dcsimg
Comparing lists
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Michael_Thompson
Posted On:   Thursday, July 27, 2006 02:48 PM

I don't know if I've posted this in the correct place. I am VERY new to OOP, and I am trying to compare two lists in a strict OOP fashion. I will try and make this as abstract as possible b/c the issue comes up frequently in my applications.

I have two lists, one is a list of items that exist in inventory (ExtantItems), and another is a list of items that should be in the inventory (RecordedItems). I want to create two more lists from these, items that don't exist, but should (NonExtantItems), and items that do exist, but shouldn't (UnRecordedItems).

Thank you for your time.

Re: Comparing lists

Posted By:   Anonymous  
Posted On:   Friday, July 28, 2006 01:14 AM

Sending you a code snippet..hope it helps...let me know in case of any other questions



package com.surjendu;



import java.util.ArrayList;


import java.util.List;


import org.apache.commons.lang.ArrayUtils;




public class CompareList {


public static void main(String[] args) {


CompareList list = new CompareList();

System.out.println(ArrayUtils.toString(list.getNonExtantItems(
list.getExtantItems(), list.getRecordedItems()).toArray()));


System.out.println(ArrayUtils.toString(list.getUnRecordedItems(
list.getExtantItems(), list.getRecordedItems()).toArray()));
}




private List getExtantItems() {


List extantItems = new ArrayList();


extantItems.add("cat");


extantItems.add("dog");


extantItems.add("camel");


extantItems.add("monkey");


extantItems.add("lamb");


extantItems.add("squirrel");


extantItems.add("chicken");


return extantItems;


}



private List getRecordedItems() {


List recordedItems = new ArrayList();


recordedItems.add("cat");


recordedItems.add("dog");

recordedItems.add("camel");

recordedItems.add("monkey");

recordedItems.add("chicken");

recordedItems.add("pig");

recordedItems.add("cow");

return recordedItems;

}



private List getNonExtantItems(List extantItems, List recordedItems) {

List nonExtantItems = new ArrayList();


for (int i = 0; i < recordedItems.size(); i++) {

if (!extantItems.contains((String) recordedItems.get(i))) {

nonExtantItems.add((String) recordedItems.get(i));

}


}

return nonExtantItems;


}



private List getUnRecordedItems(List extantItems, List recordedItems) {

List unRecordedItems = new ArrayList();


for (int i = 0; i < extantItems.size(); i++) {

if (!recordedItems.contains((String) extantItems.get(i))) {

unRecordedItems.add((String) extantItems.get(i));

}


}

return unRecordedItems;

}


}

About | Sitemap | Contact