Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare strings in two different arraylist (JAVA)

This is a pice of my code :

  ArrayList<String> Alist= new ArrayList<String>();
  ArrayList<String> Blist= new ArrayList<String>(); 

  Alist.add("gsm");
  Alist.add("tablet");
  Alist.add("pc");
  Alist.add("mouse");

  Blist.add("gsm");
  Blist.add("something");
  Blist.add("pc");
  Blist.add("something");

so i have two array list i want to compare all items and check if they are not equal and if they are to print out only the items that are not equal.

so i make something like this:

http://postimage.org/image/adxix2i13/ sorry for the image but i have somekind of bug when i post here a for looop.

and the result is :

not equals..:tablet
not equals..:pc
not equals..:mouse
not equals..:gsm
not equals..:tablet
not equals..:pc
not equals..:mouse
not equals..:gsm
not equals..:tablet
not equals..:pc
not equals..:mouse
not equals..:gsm
not equals..:tablet

i want to print only the 2 that are not equal in the example they are gsm and pc

not equals..:gsm
not equals..:pc
like image 871
user1792440 Avatar asked Sep 12 '25 10:09

user1792440


2 Answers

Don't use != to compare strings. Use the equals method :

if (! Blist.get(i).equals(Alist.get(j))

But this wouldn't probably fix your algorithmic problem (which isn't clear at all).

If what you want is know what items are the same at the same position, you could use a simple loop :

int sizeOfTheShortestList = Math.min(Alist.size(), Blist.size());
for (int i=0; i<sizeOfTheShortestList; i++) {
    if (Blist.get(i).equals(Alist.get(i))) {
        System.out.println("Equals..: " + Blist.get(i));
    }
}

If you want to get items that are in both lists, use

for (int i = 0; i < Alist.size(); i++) {
    if (Blist.contains(Alist.get(i))) {
        System.out.println("Equals..: " + Alist.get(i));
    }
}
like image 125
Denys Séguret Avatar answered Sep 15 '25 00:09

Denys Séguret


You can use the RemoveAll(Collection c) on one of the lists, if you happen to know if one list always contains them all.

like image 23
Frank Avatar answered Sep 15 '25 01:09

Frank