Compare 2 ArrayList elements

Hi,
I want to compare 2 arraylist elements and set only the elemnts which doesnot match in either of the List.
For example:-
List<String> list1 = new ArrayList<String>();
          list1.add("Italy");
          list1.add("US");
          list1.add("England");
          list1.add("Australia");
          list1.add("China");
          List<String> list2 = new ArrayList<String>();
          list2.add("Italy");
          list2.add("US");
          list2.add("England");
          List<String> finalList = new ArrayList<String>();
for (String country1 : list1) {
          for (String country2 : list2) {
          if (!country1.equalsIgnoreCase(country2)) {
               finalList.add(country1);
Here I am comparing both the arraylist elements, and in the FinalList I need capture the elements which are not matching , hence the final List should contains
Australia and China which is not there in the second arraylist (list2). But the output that is displayed for tha above is wriong as it is comparing the each elemnt of list1 with all the elemnts of list2. Instead I want list1.elemnt[0] not equals list2.elemnt[0] followed by list1.element[1] not equal to list2.element[1] , etc.
So that i can capture the elements which doesnot match and set it in the finalList. Here the output should be Australia & China. How we can do the above.
Please clarify.
Thanks.

The test is wrong.
List<String> list1 = new ArrayList<String>();
list1.add("Italy");
list1.add("US");
list1.add("England");
list1.add("Australia");
list1.add("China");
List<String> list2 = new ArrayList<String>();
list2.add("Italy");
list2.add("US");
list2.add("England");
List<String> finalList = new ArrayList<String>();
for (String s1 : list1) {
     boolean found = false;
     for (String s2 : list2) {
          if ((s1!=null && s1.equalsIgnoreCase(s2)) || s1==s2) {
               found = true;
               break;
     if (!found) finalList.add(s1);
}or you can generalize the idea and do this:
static <T> List<T> cmp(List<T> list1, List<T> list2, Comparator<T> comparator) {
     List<T> finalList = new ArrayList<T>();
     for (T s1 : list1) {
          boolean found = false;
          for (T s2 : list2) {
               if (comparator.compare(s1, s2)==0) {
                    found = true;
                    break;
          if (!found) finalList.add(s1);
     return finalList;
static final Comparator<String> stringComparator = new Comparator<String>() {
    @Override public int compare(String o1, String o2) { return o1!=null ? o1.compareToIgnoreCase(o2) : o1==o2 ? 0 : -1; }
static List<String> cmp(List<String> list1, List<String> list2) { return cmp(list1, list2, stringComparator); }
static void test() {
     List<String> list1 = new ArrayList<String>();
     list1.add("Italy");
     list1.add("US");
     list1.add("England");
     list1.add("Australia");
     list1.add("China");
     List<String> list2 = new ArrayList<String>();
     list2.add("Italy");
     list2.add("US");
     list2.add("England");
     List<String> finalList = cmp(list1, list2);
     for (String s : finalList) System.out.println(s);
}Carlo

Similar Messages

  • Problem comparing two ArrayLists, elements must match, order not important.

    Hello,
    I am new to Java and my assignment is:
    Write a method for the Purse class - public boolean sameCoins(Purse other), that checks whether the other purse has the same coins, perhaps in a different order.
    For example, the purses:
    *Purse[Quarter,Dime,Nickel,Dime]*
    and
    *Purse [Nickel,Dime,Dime,Quarter]*
    should be considered equal.
    You will probably need one or more helper methods.
    I was able to make a method to check if the purses match(sameContents), but I have not been able to check if they match just based on elements(sameCoins). We are not using Collections.
    Below is my Purse Class:
    import java.util.ArrayList;
    public class Purse {
        private ArrayList<String> coins;
        public Purse() {
            coins = new ArrayList<String>();
        public void addCoin(String coinName) {
            coins.add(coinName);
        public String toString() {
            String text = "Purse[ ";
            for (String a : coins)
                text += a;
            text += "]";
            return text;
        public boolean sameContents(Purse other) {
            boolean content = false;
            if (other.coins.equals(coins))
                content = true;
            return content;
        public boolean sameCoins(Purse other){
            boolean samecoins = true;
            for(String a: coins)
                for(String b: other.coins)
                    if (a.contains(b))
                        samecoins = true;
                    else
                        samecoins=false;
            return samecoins;
    }Any help would be appreciated.

    tipalm wrote:
    Well then my prof cant hold it against me can he!He sure can, if he wants to. I'll bet you 30 duke stars that if you hand in the program as-is and try to argue for using the Collections framework, he's going to say "I meant you couldn't use any of the static methods in the Collections framework, the whole point of the assignment was to work through the logic of iterating through the Lists" But hey, it's not my assignment, so good luck!
    Edit- I'm not saying that using the Collections framework (and its myriad static methods) is bad in any way. It's actually what you should use, assuming there are no academic "but don't use this shortcut" rules being applied. I just doubt that's your case here. I'd recommend looking into how the Collections framework works, and then implement your own algorithm based on that.
    Edited by: kevinaworkman on Oct 29, 2009 10:13 AM

  • How to compare multiple arraylists ....

    with different length?
    Imagine you´ve got one ParentArrayList, which contains one or more ArrayLists as elements. The (Child)ArrayLists contains multiple String elements of different size.
    Here is a small Graphic on this:
    Parent_ArrayList
    ####Child_ArrayList_1->element1->element2->element3
    ####Child_ArrayList_2->element1->....elementn
    ####Child_ArrayList_n->element1->element2->element3
    E.g.:I have to compare all the elements of the child_arraylists_1 with child_arraylists_2 , write all elements which are euqal into an other temparrayList.Then Compare temp arraylist with elements of Child_ArrayList_n and write it back into the temp_arraylist.
    I hope I could explain my problem?!?
    Thank you for any suggestions?!

    Hi Mehmet,
         private final static String[][] initial_data = {{"1", "2", "3", "5"},
                                                                     {"2", "3", "5", "8", "12"},
                                                                     {"3", "5", "7", "12", "20"},
                                                                     {"4", "7", "3", "9", "5", "2"},
                                                                     {"5", "9", "2", "7", "9", "0", "3"}};
         private final static List Parent_ArrayList = new ArrayList();
         static {
              for (int i = 0; i < initial_data.length; i++) {
                   final List Child_ArrayList = new ArrayList();
                   for (int j = 0; j < initial_data<i>.length; j++) {
                        Child_ArrayList.add(initial_data<i>[j]);
                   Parent_ArrayList.add( Child_ArrayList );
                   Set common = null;
                   for (Iterator iter = Parent_ArrayList.iterator(); iter.hasNext();) {
                        List element = (List) iter.next();
                        Set tempSet = new HashSet(element);
                        if(null==common) {
                             common = tempSet;
                        } else {
                             common.retainAll(tempSet);
    common will contain common string from all children.
    Best regards, Maksim Rashchynski.

  • Comparing to Photoshop Elements 4

    I'm new to digital photography editing, could someone please tell me how does Aperture compares to Photoshop Elements 4?
    How does Aperture's photo editing perform when comparing to Photoshop?

    I agree to a certain degree. Aperture's focus is to simply and streamline your photo processing. If you take a lot of pictures and want a way to quickly sort through them and make adjustments like exposure, saturation or tint, then Aperture is probably a great choice. However, if you're doing editing that involves layers and changing the background and such, you'll be much better off with Elements 4.
    Personally, I use Aperture WITH Elements (they can interface quite nicely - with Elements being your external editor for those pictures that you can fix with Aperture). Obviously, the price tag is a quite a bit different - Aperture retails for $300 while Elements retails for $100.

  • Compare the cost element of each internal order

    Hello All,
    How can we compare the cost element of each internal order?
    let me know how can we maintain the budget for each cost element for each internal order.  so that along the year, we can compare budget and actual for controlling purpose.
    Thanks
    Naveen

    Hi,
    I guess you mean comparing plan value by cost element for different IOs.
    If you want to compare those (same as actual), you could put internal orders, ranges or groups into the respecitve columns. I also did this once I think for car costs, where the manager wanted to see 10 cars next to each other and compare them (in this case it was actual figures, but same is possible with plan values).
    You just need to unselect IO on general data selection and use this as characteristic in the columns then.
    hope this helps?
    regards
    Bjoern

  • Efficient compare among vector elements

    Hi guys,
    I've a basic question, I've solved it with lots of nester for and I'm sure it's not the best way to do it, so I hope you can help me.
    I've a vector of object User, so Vector<User> and user object has a property age.
    What I want is simply:
    1) iterating this vector and make comparing of age field for each user with each user (for example, 3 user, user1 - user2, user2 -user3,user3-user1).
    2) User older for each compare must be entered in a new vector.
    So starting from a vector of n element I should have a new vector with dimension equal to n*(n-1)/2.
    Could someone help me to find most efficient code? (please show some code example)
    Thanks,
    Regards

    new_to_java123 wrote:
    What I want is simply:
    1) iterating this vector and make comparing of age field for each user with each user (for example, 3 user, user1 - user2, user2 -user3,user3-user1).
    2) User older for each compare must be entered in a new vector.
    So starting from a vector of n element I should have a new vector with dimension equal to n*(n-1)/2.Well what you want is simply a very inefficient way to solve the problem. As you describe it you will use an algorithm of complexity O(n**2), while it can be done in O(n)!
    What you should do:
    1) Parse the vector once and determine the minAge and maxAge
    2) Create an array[min-age, max-age] which contains a list of users for each index. As this is not directly supported in Java, use an ArrayList of size (maxAge - minAge ++1) and populate it with an empty List for each index 0 .. maxAge - minAge. Each entry with index i in that ArrayList is a List of persons whose age is (i ++ minAge).
    3) Now iterate over the original Vector and append each user to the List of persons of his age (in code: ageList.get(user.getAge() - minAge()).add(user); )
    Voilá. Only two scans of the original Vector and you have a structure that holds
    1) List of the users of a given age (ageList.get(age - minAge()).
    2) All users older than the given age can be found by iterating the lists with greater index as (age - minAge()).
    And of course the memory requirements are much lower also!
    It needs to store only maxAge - minAge + 1 plus the outer ageList. if you store null instead of an empty list if no user has a specific age this can be further reduced at the cost of havein to do more null checks.

  • How to get count,index and compare to arraylists

    hi
    how to get count,index and comparing of 2 arraylist.... plz suggest me asap...

    How is your question related to JDBC? And what have you done so far with your code?

  • PE 13: Upload to Youtube performance much worse compared with Premiere Elements 10

    Since a week I have premiere Elements 13 purchased and installed and the first experience after creating three movies and uploading them to youtube is that I am thinking of going back to PE version 10. Uploading of a movie of 5 minutes takes more than 70 minutes!! In premiere Elements 10 it was much faster (approx.10-15 minutes. I have broadband glassfiber connection (just tested speed:90MB/s)
    It seems an authentication/firewall kind of protocol is unacceptably slowing down the upload to youtube.
    What could I do in settings to improve speed?
    Kind regards, Fred

    Fred
    What computer operating system is your Premiere Elements 13 running on? Same one as Premiere Elements 10?
    Have you ever run Premiere Elements 10 on the same computer as 13 for YouTube comparisons with the same upload content?
    You seem to have found the cause of the problem since you wrote
    It seems an authentication/firewall kind of protocol is unacceptably slowing down the upload to youtube.
    What is your evidence for that? And, where do you believe the firewall to be in your computer operating system, buried with the authorization process of the Premiere Elements feature, or other?
    With your present Premiere Elements 13 Timeline content and export to file, do you find faster uploading to YouTube at the YouTube web site
    as compared to uploading the file with that same content to YouTube from within the Premiere Elements 13 feature?
    ATR

  • Anyone using Gimp on OSX?  Compared to PS Elements?

    Looking to design my own logos/leterhead etc.  My PS Eelements4.0 is not working on iMac (too old a version).
    before I buy the latest PS Eelements, I'm downloading Gimpfo rfree.  Anyone compared both?  Would love your feedback.  Will let you know how I find using Gimp once I play with it.

    Just tried playing with gimp and I see what you mean.  If I take the time to read the manual, I can see it has most the same features for my purposes.  I also just tried Inkscape (free also) and that has some interesting features as well.  Worth investing some graphics playtime in both before I buy a current version of PSE.  I suspect you're right though - when pressed to complete a project, I'll run out to buy what I know - PSE.  Same reason I'm still using MSWord and Excel instead of iWork.

  • Help comparing two ArrayList initializations instructions.

    I found these two methods to initialize ArrayList on a single row in a 3 years old topic here in this forum... so I open a new thread to ask you what you think is the best method I could use. Thank you!
        private static ArrayList<String> strSearchs = new ArrayList<String>(){{add(" state changed from Full to ");}};
        private static ArrayList<String> strSearchs2 = (ArrayList<String>)Arrays.asList(" state changed from Full to ");PS: note that original suggestions was for "List" objects, so I had to add a cast to "ArrayList" in the second instruction.

    Pratically I have such objects which get a String (we can call it "*strOrig*") in the constructor. As result it parse the String, and store all parsed informations in object's variables\attributes.
    Obviously the String is checked to control if it fits some parameters before parsing starts. The static ArrayList contains further requisites (Strings which have to "match" with "*strOrig*" content to confirm it is valid) which are chosen by "the user" (I mean who implements these kind of classes).
    It mean that I need to make the ArrayList modificable (both substituted by another ArrayList variable, or adding, changing and/or removing content for the existing one). I made it static, so it will not create a new ArrayList for every instantiate object.
    So if List can't support add and similar, I think it's not my case. :-S
    Maybe I could instantiate the ArrayList in an AbstractList object, so also Vector could also be used bye "the user"... but this is not very related.
    So maybe private static AbstractList<String> strSearchs = new ArrayList<String>(Arrays.asList(" state changed from Full to ")); is my case...
    Do you agree with me?
    WalterLaan wrote:
    ThePatcha wrote:
    The variable is not intended to be Final, it can be modified via static methods, but I need it's static (so unique for every object instantiated) and it starts with a defaul value already inside.static means the opposite: it is the same for all instances, not unique per instance.My fault: I meant "it's always the same for all instanced objects". I used "unique" instead of "always the same", sorry.
    Edited by: ThePatcha on Feb 2, 2010 6:45 AM

  • How to change elements in ArrayList into String

    Greetings,
    i like to change elements in arrayList into string.
    This is how i declare an ArrayList in a Java file
    ArrayList listing = new ArrayList();below is just a simple example of how i insert the string into the arraylist
    String concat = "';
    concat = concat + "apple";
    //Transfer the concat string into arraylist
    listing.add(concat);
    return listing;
    {code}
    On my Jsp page, it will receive the ArrayList from the java file. Lets say the Arrayist is pass into my JSP arraylist
    This is my JSP arraylist
    {code}ArrayList optLists = new ArrayList();{code}
    Inside the arraylist element, it holds data eg: *308577;;RS | [CAT 2] Level: Arena, Section: A02* with a pipe between RS and CAT 2.
    Now i looping the arraylist
    {code}int a = 0;
         for ( a=0; a < optLists.size(); a++)
              String tempString = "";
              String splitTemp = "";
                     String tempString = (String)optLists.get(a);
              splitTemp =  tempString.split("|");
              System.out.println("Split String Results: "+ splitTemp);
         {code}}
    Heres the error:
    *SeatAvailable_jsp.java:560: incompatible types*
        *[javac] found   : java.lang.String[]*
        *[javac] required: java.lang.String*
        *[javac]             splitTemp =  tempString.split("|");*
        *[javac]*       
    What can i do to solve the problem?
    Edited by: leeChaolan on May 2, 2008 4:45 AM
    Edited by: leeChaolan on May 2, 2008 4:48 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    paternostro is right, you are returning an array into a string which is wrong
    but try this, i haven't tested it though..
    nt a = 0;
         for ( a=0; a < optLists.size(); a++)
              String tempString = "";
              String splitTemp = "";
                     String tempString = (String)optLists.get(a);
              String[] splitTemp =  tempString.split("|");
              for(String xyz : splitTemp)
                   System.out.println("Split String Results: "+ xyz);
         }Edited by: linker on May 2, 2008 1:17 PM
    Edited by: linker on May 2, 2008 1:18 PM

  • Shall we compare two elements in a collection

    Dear all,
    shall we compare two scuccessive elements in a collection
    i am creating a type.and i am dumping the data into that type using bulk collect.now i need to compare the data in type (previous value and current value).
    please suggest
    Thank you.
    Suresh

    899511 wrote:
    Dear all,
    shall we compare two scuccessive elements in a collection
    i am creating a type.and i am dumping the data into that type using bulk collect.now i need to compare the data in type (previous value and current value).
    please suggest
    Thank you.
    SureshDon't do it in a collection. Use SQL.
    SQL provides Lead and Lag analytical function that allow you to compare next/previous values.
    e.g.
    http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions070.htm
    Loading the data into a collection in memory to do something that can be easily achieved in SQL is just wrong and uses expensive PGA memory unnecessarily.

  • Comparing elements inside a vector

    Hello,
    I am having a hard time understanding how to compare elements inside a vector. I have a vector of six strings and I want to compare the first element at index 0 with all other elements at positions 1-5. After that, compare the element at position 1 with elements at positions 2-5 and so on until all elements have been compared against each other.
    Can some one please advise me on how to achieve this?
    Thank you.

    joor_empire wrote:
    Thanks for replying. I tried using nested loops, but I keep getting array index out of bound error.Hmmm, then you're doing it wrong.
    For more information, you'll have to give us more info, such as your code (please use code tags when posting it though).

  • Comparing array elements for equality

    Hi
    I have written a simple program that works as a lottery number predictor. It works fine except for the fact that sometimes 2 numbers will be the same. Does anyone know of a method that compares an array element to the others to test for equality?

    ok I've had a go at implementing a solution. I worked it out on paper so I haven't tested it yet in the program. Let me know if you can see any errors that I can't.
       boolean numNotSame = true;
       int[] lottery = new int[5];
       int currentNumber;
       start:  //label to return to if 2 numbers are the same
       while(numNotSame){
          for( int j = 0; j < lottery.length; j++){
              currentNumber = 1 + randomNumbers.nextInt(34);   //get random number
              for( int i = 0; i < lottery.length; i++){
                 if( currentNumber == lottery)
    continue start; //if numbers are the same begin again
    } //end inner for
    lottery[ j ] = currentNumber; //set array element if number not used yet
    } //end outer for loop
    numNotSame = false; //set false so while loop will end
    } //end while block

  • Old Elements to compare with CS6

    I want to compare my old Elements 10  that I had on my windows CPU with the CS6 I want to cancel. I can not pull up Elements.  How do I retrieve it back?
    U

    I finally found my old cd and it first said to remove the old one. So I did
    and while it was re exe. a message said I had a Newer version and it stop
    loading. I believe it to be the CS6 Photo shop. and any rate each time I
    tried I got the same message.  So if I am right? Photo shop is the same?
    some has extra bells and stuff am I correct?

Maybe you are looking for