Looking through inventory for multiple items

Discussion in 'Spigot Plugin Development' started by theboyjamal, Apr 30, 2017.

  1. Basically im making a quest-like plugin where a player would put lets say 16 wood, 64 cobblestone, and 3 diamonds. And the quest would only complete if all those items with the right amount are in there. the problem is the way i currently do it, it loops 3 times and runs the command 3 times, but if i return once it gets to the reward code, it only searches through one item defined in the yml. Any suggestions?
  2. So by that you are searching for something that is easier than 3 loops and 3 commands or what?
    Edit: Maybe provide your code so we can check through because some people may don't understand what you are trying
  3. You could use the Inventory#all(ItemStack itemStack) method to count your items. A method like this should work:
    Code (Text):
        private int getItemAmount(Inventory inventory, ItemStack item) { // Not tested
            return inventory.all(item).values().stream().mapToInt(ItemStack::getAmount).sum();
    Ofc you would still need to loop through all required items and their required amounts

    Edit: (Explanation)
    Inventory#all(ItemStack itemStack) returns a HashMap<Integer, ItemStack> with the 'Integer part' being the slot and 'ItemStack part' being the actual ItemStack in that slot. Then HashMap#values to get only the ItemStacks, Set#stream to get its stream and map it to an ArrayList<Integer> with the ItemStacks amount being the content of that List. The #sum method then creates the sum of all amounts
    #3 Syranda, Apr 30, 2017
    Last edited: Apr 30, 2017
  4. That's a good way but rip to the java 7 or lower people :p
  5. Added an explanation. Thank you :)

    Java 8 master race xD
  6. that doesn't really help as i need to look at each item to check for certain item typeid, lore, amount per item etc @Syranda
  7. Then you could make a stream of the inventory contents and then filter the items to your needs. The part #mapToInt(ItemStack::getAmount)#sum() stays the same
  8. Try asking the makers of betonquest for tips!
    • Like Like x 1
  9. @Mctoplist they have open source so ill look through that. thanks for the suggestion!
    • Agree Agree x 1
  10. okay ill try it out