Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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[6] = 1

Thanks in advance

like image 506
user438159 Avatar asked Aug 24 '11 10:08

user438159


People also ask

Can we compare two ArrayList?

The ArrayList. equals() is the method used for comparing two Array List. It compares the Array lists as, both Array lists should have the same size, and all corresponding pairs of elements in the two Array lists are equal. Parameters: This function has a single parameter which is an object to be compared for equality.

How do I compare two lists in java8?

You need to override equals() method in SchoolObj class. contains() method you will uses the equals() method to evaluate if two objects are the same. But better solution is to use Set for one list and filter in another list to collect if contains in Set. Set#contains takes O(1) which is faster.

How do I compare two lists in Java and get differences?

Using the Java List API. We can create a copy of one list and then remove all the elements common with the other using the List method removeAll(): List<String> differences = new ArrayList<>(listOne); differences. removeAll(listTwo); assertEquals(2, differences.


1 Answers

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]
like image 174
dacwe Avatar answered Oct 06 '22 21:10

dacwe