Compare two arraylist

I have two Arraylists:

ArrayList a1 = new ArrayList();
a1.add("5");
a1.add("10");
a1.add("20");
a1.add("50");
a1.add("100");
a1.add("500");
a1.add("1000");

ArrayList a2 = new ArrayList();
a2.add("50");
a2.add("500");
a2.add("1000");

How can I compare these two arraylists and add to the new arraylist (a3) ​​with 1 if a2 exists in a1 and 0 if it does not exist, so the result will be lower for arraylist a3?

a3[0] = 0
a3[1] = 0
a3[2] = 0
a3[3] = 1
a3[4] = 0
a3[5] = 1
a3[6] = 1

Thanks in advance

+5
source share
5 answers

First, I would advise you to use generics . And secondly, for a2maybe Set. And thirdly, you may need to change from Stringto Integer(since they are all integers).

But for your example, this is the way to do this:

ArrayList<Integer> a3 = new ArrayList<Integer>();               
for (String a : a1)
    a3.add(a2.contains(a) ? 1 : 0);

Full example (with type HashSetand Integer):

public static void main(String... args) {
    List<Integer> a1 = Arrays.asList(5, 10, 20, 50, 100, 500, 1000);
    Set<Integer>  a2 = new HashSet<Integer>(Arrays.asList(50, 500, 1000));

    ArrayList<Integer> a3 = new ArrayList<Integer>();                

    for (Integer a : a1)
        a3.add(a2.contains(a) ? 1 : 0);

    System.out.println(a3);
}

Conclusion:

[0, 0, 0, 1, 0, 1, 1]
+11
source

It will do it.

, int[] , , . , , , , , , .

public static void main(String[] args) {
    ArrayList<String> a1 = new ArrayList<String>();
    a1.add("5");
    a1.add("10");
    a1.add("20");
    a1.add("50");
    a1.add("100");
    a1.add("500");
    a1.add("1000");

    ArrayList<String> a2 = new ArrayList<String>();
    a2.add("50");
    a2.add("500");
    a2.add("1000");

    int[] matches = new int[a1.size()];

    int i = 0;
    for (String s : a1)
        matches[i++] = a2.contains(s) ? 1 : 0;

    System.out.println(Arrays.toString(matches));
}

:

[0, 0, 0, 1, 0, 1, 1]
+1

You can use contains(Object o) method of ArrayListto check whether this element is present in the second arraylist or not, and, accordingly, add the element to the 3rd list, for example:

for(String temp: a1)
{
   if(a2.contains(temp)) 
   {
      a3.add(1);
   }
   else
   {
     a3.add(0);
   }
}
+1
source

Pseudo code

Check both a1 and a2 for length. say a1 is longest
a3 = new arraylist(a1.length) 
for(i=0 to a2.length)
 if(a1.contains(a2.get(i))
  a3.get(i)++;
0
source

Something like that:

ArrayList<Integer> a3 = new ArrayList<Integer>();

for (String v : a1) {
    if (a2.contains(v)) {
        a3.add(1);
    } else {
        a3.add(0);
    }
}
0
source

All Articles