Created
July 5, 2020 18:10
-
-
Save kBULOSU/6f3cdc6ace29984a132955852eb42f6e to your computer and use it in GitHub Desktop.
ItemStack builder with Functional Interfaces.
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
import org.bukkit.Material; | |
import org.bukkit.inventory.ItemStack; | |
import org.bukkit.inventory.meta.ItemMeta; | |
import java.util.Arrays; | |
import java.util.LinkedList; | |
import java.util.List; | |
import java.util.function.BiConsumer; | |
import java.util.function.BiPredicate; | |
import java.util.function.Supplier; | |
public class ItemBuilder implements Supplier<ItemStack> { | |
private final List<BiConsumer<ItemStack, ItemMeta>> biconsumerList; | |
private final Material material; | |
public ItemBuilder(Material material) { | |
this.biconsumerList = new LinkedList<>(); | |
this.material = material; | |
} | |
public ItemBuilder with(BiConsumer<ItemStack, ItemMeta> biconsumer) { | |
biconsumerList.add(biconsumer); | |
return this; | |
} | |
public ItemBuilder withIf(BiPredicate<ItemStack, ItemMeta> bipredicate, BiConsumer<ItemStack, ItemMeta> biconsumer) { | |
return with((stack, meta) -> { | |
if (bipredicate.test(stack, meta)) { | |
biconsumerList.add(biconsumer); | |
} | |
}); | |
} | |
public ItemBuilder withIfOrElse(BiPredicate<ItemStack, ItemMeta> bipredicate, BiConsumer<ItemStack, ItemMeta> ifTrue, BiConsumer<ItemStack, ItemMeta> ifFalse) { | |
return with((stack, meta) -> { | |
if (bipredicate.test(stack, meta)) { | |
biconsumerList.add(ifTrue); | |
return; | |
} | |
biconsumerList.add(ifFalse); | |
}); | |
} | |
public ItemBuilder withAmount(int amount) { | |
return with((stack, meta) -> stack.setAmount(amount)); | |
} | |
public ItemBuilder withDurability(int durability) { | |
return with((stack, meta) -> stack.setDurability((short) durability)); | |
} | |
public ItemBuilder withLoreIf(BiPredicate<ItemStack, ItemMeta> bipredicate, String... lore) { | |
return withIf(bipredicate, (stack, meta) -> meta.setLore(Arrays.asList(lore))); | |
} | |
public ItemBuilder withNameIfOrElse(BiPredicate<ItemStack, ItemMeta> bipredicate, String | |
name, BiConsumer<ItemStack, ItemMeta> biconsumer) { | |
return withIfOrElse(bipredicate, (stack, meta) -> meta.setDisplayName(name), biconsumer); | |
} | |
@Override | |
public ItemStack get() { | |
ItemStack item = new ItemStack(material); | |
ItemMeta meta = item.getItemMeta(); | |
biconsumerList.forEach(biconsumer -> biconsumer.accept(item, meta)); | |
item.setItemMeta(meta); | |
return item; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment