Steven Spieler
Steven Spieler

Reputation: 125

How to check if a list has the same elements as another list, being able to have duplicate

I have 2 lists with different types of names of citys:

ArrayList<City> list1 = new ArrayList<City>();
ArrayList<City> list2 = new ArrayList<City>();


list1.add(Birmingham);
list1.add(Amsterdam);
list1.add(Rotterdam);
list1.add(Brussels);

list2.add(Brussels);
list2.add(Brussels);
list2.add(Rotterdam);
list2.add(Amsterdam);
list2.add(Amsterdam);

if i compare these 2 lists, it should be true

if i have a third list:

list3.add(brussELtss);
list3.add(Rotterdam);
list3.add(Amsterdam);

If i compare the third list to either of the first 2 it should be false

I tried comparing, equals and containsall, but that doesnt work.

Upvotes: 0

Views: 340

Answers (1)

M Sach
M Sach

Reputation: 34424

You have set for this, Have a look at Hashset implementation which will containing the unique element. Your object City needs to implement Comparable/Comparator to decide on equality. Add first element in set and then start adding second list, if add method returns true then element is already there

Update :- After reading comment, i can think of below O(n) time complexity Algo

  1. Iterate over first list and construct a map(HashMap as implemetaion) with element as key and count as value

  2. Iterate over second list, if element does not exist in map they are not equal.

  3. If element found, reduce the count by one for that element in map

  4. At last iterate over map, if there is an element with count other than zero, then list are not equal

Upvotes: 1

Related Questions