How can I return the difference between two lists?

后端 未结 10 686
终归单人心
终归单人心 2020-11-27 03:49

I have two array lists e.g.

List a;
contains : 10/10/2014, 10/11/2016

List b;
contains : 10/10/2016

How can i do

10条回答
  •  忘掉有多难
    2020-11-27 04:48

    I was looking for a different problem and came across this, so I will add my solution to a related problem: comparing two Maps.

        // make a copy of the data
        Map a = new HashMap(actual);
        Map e = new HashMap(expected);
        // check *every* expected value
        for(Map.Entry val : e.entrySet()){
            // check for presence
            if(!a.containsKey(val.getKey())){
                System.out.println(String.format("Did not find expected value: %s", val.getKey()));
            }
            // check for equality
            else{
                if(0 != a.get(val.getKey()).compareTo(val.getValue())){
                    System.out.println(String.format("Value does not match expected: %s", val.getValue()));
                }
                // we have found the item, so remove it 
                // from future consideration. While it 
                // doesn't affect Java Maps, other types of sets
                // may contain duplicates, this will flag those
                // duplicates. 
                a.remove(val.getKey());
            }
        }
        // check to see that we did not receive extra values
        for(Map.Entry val : a.entrySet()){
            System.out.println(String.format("Found unexpected value: %s", val.getKey()));
        }
    

    It works on the same principle as the other solutions but also compares not only that values are present, but that they contain the same value. Mostly I've used this in accounting software when comparing data from two sources (Employee and Manager entered values match; Customer and Corporate transactions match; ... etc)

提交回复
热议问题