简体   繁体   中英

Compare 2 lists in java and return the difference

Hello I am using selenium with java. I have to compare lists and return the difference.These values i am fetching from the database

List A has IDs and Income Tax, List B has Ids and Income tax.

I want to compare List A Ids with List B Ids and List A Income tax with List B Income tax. After compare I want to return the difference.i,e

Example :If IDS in List A [1,2,3] and Income Tax in List A are [10.25,1.58,30.28]

Ids in List B[1,2,3] and Income Tax in List B are [10.25,1.57,28.28]

I want to display which values are different after comparison and also for which IDs its different

I want output as Income tax is different for Ids 2 and 3.

For comparing the lists I tried the below code

try {
    IDList.equals(AfterChangeIDList);
        log.info("ID List are equal");
    }catch (Exception e) {
        log.warn("IDList are not equal");
        throw e;
    }

//Compare Income tax lists

try {
        IncomeTaxList.equals(AfterChangeIncomeTaxList);
        log.info("Income Tax list are equal");
    }catch (Exception e) {
        log.warn("Income Tax list are not equal");
        throw e;        
    }

May I know how to return the difference?

Please try the following:

public void test() {
        List<Integer> ids = new ArrayList<>();
        ids.add(1);
        ids.add(2);
        ids.add(3);
        List<Double> taxes = new ArrayList<>();
        taxes.add(10.25d);
        taxes.add(1.58d);
        taxes.add(30.28d);
        List<Double> taxes2 = new ArrayList<>();
        taxes2.add(10.25d);
        taxes2.add(1.57d);
        taxes2.add(28.28d);

        List<Integer> differentIds = new LinkedList<>();
        for (int i = 0; i < ids.size(); i++) {
            if (!taxes.get(i).equals(taxes2.get(i))) {
                differentIds.add(ids.get(i));
            }
        }
        System.out.println("Different values for ids: " + differentIds);
    }
public static void main(String[] args) {

    List<Integer> ids = List.of(1, 2, 3);
    List<Double> taxes = List.of(10.25, 1.58, 30.28);
    List<Double> taxes2 = List.of(10.25, 1.57, 28.28);

    for (int i = 0; i < ids.size(); i++) {
        int id = i + 1;
        int result = taxes.get(i).compareTo(taxes2.get(i));

        if (result != 0) {
            System.out.println(
                    "value for id:" + id
                            + " is changed  old value: " + taxes.get(i)
                            + ",new value is: " + taxes2.get(i));
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM