开发者

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 this two arraylists and add into new arraylist(a3) with 1 if a2 exist in a1 and 0 if not exist, so the result will below for arraylist a3?

a3[0] = 0
a3[1] = 0
a3[2] = 0
a3[3] = 1
a3[4] = 0
a3[5] = 1
a3[开发者_Go百科6] = 1

Thanks in advance


First, I would advice you to use generics. And secondly, for a2 could be a Set instead. And thirdly you might want to change from String to Integer (since they are all integers).

But for your example this is a way to do it:

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

Full example (with a HashSet and Integer type):

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);
}

Output:

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


This will do it.

Note that your question specifies int[] as the output type, which is not what I would have chosen - List would probably be better, however this answer does what you asked for, unlike every other answer I have seen so far.

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));
}

Output:

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


You can use contains(Object o) method of ArrayList to check if the element is present in 2nd arraylist or not and accordingly add the element to 3rd list like :

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


Psuedo 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)++;


Something like this:

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

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜