Skip to content

Instantly share code, notes, and snippets.

@Cryptite
Created June 6, 2019 14:47
Show Gist options
  • Save Cryptite/35a8c0a2f198b742adfdbcb52db283d3 to your computer and use it in GitHub Desktop.
Save Cryptite/35a8c0a2f198b742adfdbcb52db283d3 to your computer and use it in GitHub Desktop.
Comparable<ItemStack>
@NotNull
private Comparator<ItemStack> itemStackComparator() {
return (o1, o2) -> {
//Sort first by their order in storableItems (left to right)
ItemStack o1BaseItem = getBaseItem(o1);
ItemStack o2BaseItem = getBaseItem(o2);
List<ItemStack> storablesList = new ArrayList<>(storableItems.keySet());
int compare = Integer.compare(storablesList.indexOf(o1BaseItem), storablesList.indexOf(o2BaseItem));
if (compare != 0) return compare;
if (o1BaseItem.isSimilar(o2BaseItem)) {
//If the two base items are the same...
if (o1.getType() == Material.ENCHANTED_BOOK) {
Map.Entry<Enchantment, Integer> enchantment = getFirstEnchantment(o1, true);
Map.Entry<Enchantment, Integer> enchantment2 = getFirstEnchantment(o2, true);
if (enchantment != null && enchantment2 != null) {
Enchantment key = enchantment.getKey();
Enchantment key2 = enchantment2.getKey();
if (key.getKey().equals(key2.getKey())) {
//If they share the same first enchantment, compare the enchant level
compare = Integer.compare(enchantment2.getValue(), enchantment.getValue());
if (compare != 0) return compare;
} else {
//Compare just based on key name? Which I suppose would be alphabetical
compare = key.getKey().getKey().compareTo(key2.getKey().getKey());
if (compare != 0) return compare;
}
}
} else if (o1.getType() == Material.FIREWORK_ROCKET) {
FireworkMeta fireworkMeta = (FireworkMeta) o1.getItemMeta();
FireworkMeta fireworkMeta2 = (FireworkMeta) o2.getItemMeta();
compare = Integer.compare(fireworkMeta2.getPower(), fireworkMeta.getPower());
if (compare != 0) return compare;
}
//Compare by durability
if (o1.getItemMeta() instanceof Damageable) {
Damageable damageable = (Damageable) o1.getItemMeta();
if (damageable.getDamage() > 0) {
compare = Integer.compare(damageable.getDamage(), ((Damageable) o2.getItemMeta()).getDamage());
if (compare != 0) return compare;
}
}
}
compare = Integer.compare(o1.hashCode(), o2.hashCode());
if (compare != 0) return compare;
//At this point, these are identical items based on item hashcode. Player heads are a good example of
//things like this. Does it have a display name?
String displayName = getDisplayName(o1);
String displayName2 = getDisplayName(o2);
if (displayName != null && displayName2 != null) {
compare = displayName.compareTo(displayName2);
if (compare != 0) return compare;
}
//Ok how's about comparing itemstack size.
compare = Integer.compare(o2.getAmount(), o1.getAmount());
if (compare != 0) return compare;
TheArtifact.log.warning(this.toString() + " Comparison between " + o1 + " and " + o2 + " is 0!");
return 1;
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment