Last active
September 15, 2020 07:41
-
-
Save appkr/614fc32aa6f3119663c15ee421cb1ac2 to your computer and use it in GitHub Desktop.
Java Collection Comparison
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Elem { | |
public String key; | |
public String value; | |
public Elem (String key, String value) { | |
this.key = key; | |
this.value = value; | |
} | |
public boolean equals(Object o) { | |
Elem other = (Elem) o; | |
return key.equals(other.key) | |
&& value.equals(other.value); | |
} | |
} | |
Elem e1 = new Elem("one", "1"); | |
Elem e2 = new Elem("two", "2"); | |
Elem e3 = new Elem("one", "1"); | |
Elem e4 = new Elem("two", "2"); | |
List<Elem> l1 = new ArrayList<>(Arrays.asList(e1, e2)); | |
List<Elem> l2 = new ArrayList<>(Arrays.asList(e3, e4)); | |
l1.equals(l2); // true |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Elem { | |
public String key; | |
public String value; | |
public Elem (String key, String value) { | |
this.key = key; | |
this.value = value; | |
} | |
public boolean equals(Object o) { | |
Elem other = (Elem) o; | |
return key.equals(other.key) | |
&& value.equals(other.value); | |
} | |
} | |
public class ElemComparator implements Comparator<Elem> { | |
@Override | |
public int compare(Elem a, Elem b) { | |
return a.key.compareTo(b.key); | |
} | |
} | |
Elem e1 = new Elem("one", "1"); | |
Elem e2 = new Elem("two", "2"); | |
Elem e3 = new Elem("one", "1"); | |
Elem e4 = new Elem("two", "2"); | |
List<Elem> l1 = new ArrayList<>(Arrays.asList(e1, e2)); | |
List<Elem> l2 = new ArrayList<>(Arrays.asList(e4, e3)); | |
l1.sort(new ElemComparator()); | |
l2.sort(new ElemComparator()) | |
l1.equals(l2); // true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment