Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare two String[] arrays and print out the strings which differ

Tags:

java

arrays

I've got a list of all the file names in a folder and a list of files which have been manually "checked" by a developer. How would I go about comparing the two arrays such that we print out only those which are not contained in the master list.

public static void main(String[] args) throws java.lang.Exception {
        String[] list = {"my_purchases", "my_reservation_history", "my_reservations", "my_sales", "my_wallet", "notifications", "order_confirmation", "payment", "payment_methods", "pricing", "privacy", "privacy_policy", "profile_menu", "ratings", "register", "reviews", "search_listings", "search_listings_forms", "submit_listing", "submit_listing_forms", "terms_of_service", "transaction_history", "trust_verification", "unsubscribe", "user", "verify_email", "verify_shipping", "404", "account_menu", "auth", "base", "dashboard_base", "dashboard_menu", "fiveohthree", "footer", "header", "header_menu", "listings_menu", "main_searchbar", "primary_navbar"};
        String[] checked = {"404", "account_menu", "auth", "base", "dashboard_base", "dashboard_menu", "fiveohthree", "footer", "header", "header_menu", "listings_menu"};

        ArrayList<String> ar = new ArrayList<String>();

            for(int i = 0; i < checked.length; i++)
                {
                    if(!Arrays.asList(list).contains(checked[i]))
                    ar.add(checked[i]);
                }
    }
like image 736
Martin Erlic Avatar asked Dec 19 '22 18:12

Martin Erlic


1 Answers

Change your loop to :

ArrayList<String> ar = new ArrayList<String>();

for(int i = 0; i < checked.length; i++) {
      if(!Arrays.asList(list).contains(checked[i]))
      ar.add(checked[i]);
}

ArrayList ar should be outside of the for loop. Otherwise ar will be created every time when element of checked array exists in list.

Edit:

if(!Arrays.asList(list).contains(checked))

With this statement you are checking whether the checked reference is not the element of list. It should be checked[i] to check whether the element of checked exists in list or not.

If you want to print elements in list that are not in checked. Then use :

for(int i = 0; i < list.length; i++) {
      if(!Arrays.asList(checked).contains(list[i]))
      ar.add(list[i]);
}
System.out.println(ar);
like image 187
SatyaTNV Avatar answered Dec 21 '22 11:12

SatyaTNV