java - Compare two List<E> regardless of order -
i have 2 e type lists list list1, list list2. e object pojo class contains row of following data. both of lists contain same data. example @ last column if change false true cannot detect.
| statusid | statusname | statusstate | isrequire | | 3 | approved | approved | false | | 201 | attributed | rejected | true | | 202 | denied | rejected | false | | 204 | fraud | rejected | false | | 205 | insufficient | rejected | false | | 206 | invalid | rejected | false | | 207 | cancelled | rejected | false | | 208 | cannot traced | rejected | false | | 209 | transaction online | rejected | false | | 210 | voucher | rejected | false | | 211 | not meet req | rejected | false |
i want write function if data 2 lists different can detectected. following code seems give 'false' whether data same or different in both lists.
private boolean comparelists(list<status> actualstatuses, list<status> expectedstatuses) { boolean indicator = false; if (actualstatuses!= null && expectedstatuses!=null && actualstatuses.size() == expectedstatuses.size()){ (status expectedstatusdata : expectedstatuses){ for(status actualstatusdata : actualstatuses){ if(actualstatusdata.getstatusid() == expectedstatusdata.getstatusid() && actualstatusdata.getstatusname().equals(expectedstatusdata.getstatusname()) && actualstatusdata.getstatusstate().equals(expectedstatusdata.getstatusstate()) && actualstatusdata.isenable() == expectedstatusdata.isenable() && actualclaimstatusdata.isrequire() == expectedstatusdata.isrequire()){ indicator = true; break; } else indicator = false; } } if (indicator) return true; } else return false; return indicator; }
a better way of doing (assuming list doesn't contain repeated values) store elements of 1 list in hashset
, check if hashset
contains of elements of other list , sizes same.
private <e> boolean listshavesameelements(final list<e> l1, final list<e> l2) { final set<e> set = new hashset<>(l1); return l1.size() == l2.size() && set.containsall(l2); }
this o(n+m)
solution while using list.containsall()
need iterate elements of other list check existence o(n*m)
Comments
Post a Comment