Compression Method

 avatar
unknown
java
3 years ago
2.2 kB
10
Indexable
    /**
     * Iterates over every item in the given List, tracks the amount of items in each,
     * and generates a compressed list of ItemStacks.
     * @param list The list to compress.
     * @return The compressed list.
     */
    public List<ItemStack> compress(List<ItemStack> list) {
        Map<ItemStack, Integer> generationMap = new HashMap<>();  // The map holding the stacks and their amount.

        // Iterate over every item in the list and count the amount of each.
        for (ItemStack item : list) {

            // Creates a pivot ItemStack to use for comparison.
            ItemStack pivot = item.clone();
            pivot.setAmount(1);

            if (generationMap.containsKey(pivot))
                generationMap.put(pivot, generationMap.get(pivot) + item.getAmount());

            else { generationMap.put(pivot, item.getAmount()); }
        }

        // Generates the correct ItemStacks given the generationMap.
        List<ItemStack> compressedList = new ArrayList<>();
        for (ItemStack item : generationMap.keySet()) {

            do {
                int amount = item.getMaxStackSize();  // Defaults the itemstack amount to the max stack size.

                // If the amount left is greater than the stack size, diminish the amount left by the stack size.
                if (generationMap.get(item) > amount)
                    generationMap.put(item, generationMap.get(item) - amount);

                else {
                    // If not, change the amount to what's left, and do the same.
                    amount = generationMap.get(item);
                    generationMap.put(item, generationMap.get(item) - amount);
                }

                // Create a clone of the itemstack, change the item count, and add it to the compressed list.
                ItemStack itemClone = item.clone();
                itemClone.setAmount(amount);
                compressedList.add(itemClone);

            }
            // Keep repeating this until the amount of items left is 0.
            while (generationMap.get(item) != 0);
        }

        return compressedList;
    }
Editor is loading...