Skip to content

Instantly share code, notes, and snippets.

@mismatch
Created January 15, 2017 11:15
Show Gist options
  • Save mismatch/75f913ee2b13fd61ce14ec93ce19652c to your computer and use it in GitHub Desktop.
Save mismatch/75f913ee2b13fd61ce14ec93ce19652c to your computer and use it in GitHub Desktop.
import java.util.*;
public class TreeSetWithDuplicates {
public static void main(String[] args) {
System.out.println(removeDuplicates(Arrays.asList(
new TestItem("Book A", "First edition"),
new TestItem("Book C", "First edition"),
new TestItem("Book ABC", "Not published"),
new TestItem("Book A", "First edition"))));
}
static List<TestItem> removeDuplicates(List<TestItem> items) {
TreeSet<TestItem> uniqueItems = new TreeSet<>(TreeSetWithDuplicates::compareItems);
uniqueItems.addAll(items);
return new ArrayList<>(uniqueItems);
}
static int compareItems(TestItem item1, TestItem item2) {
if (item2.name.equalsIgnoreCase(item1.name)) {
return 0;
}
return 1;
}
static class TestItem {
private final String name;
private final String description;
TestItem(String name, String description) {
this.name = name;
this.description = description;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TestItem testItem = (TestItem) o;
return Objects.equals(name, testItem.name) &&
Objects.equals(description, testItem.description);
}
@Override
public int hashCode() {
return Objects.hash(name, description);
}
@Override
public String toString() {
return "TestItem{" +
"name='" + name + '\'' +
", description='" + description + '\'' +
'}';
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment