计算列表中的所有类似对象

时间:2017-12-29 12:44:19

标签: java list

我有一个对象列表(他们总是不喜欢这个,有更少或更多,这取决于)

[1xtile.air@0, 1xtile.air@0, 16xitem.enderPearl@0, 64xitem.eyeOfEnder@0, 16xitem.enderPearl@0, 64xitem.blazeRod@0, 1xitem.enchantedBook@0, 64xitem.blazeRod@0, 16xitem.enderPearl@0, 64xitem.eyeOfEnder@0, 16xitem.enderPearl@0]

就像你看到它们中的大多数具有相同的名称一样,这个对象有getCount()方法,它返回一个对象中的项目数量。 我想知道我怎么能合并所有具有相同名称的对象(我用getUnlocalizedName()得到对象名称)但是用每个对象的getCount()增加它们的计数,所以例如我有

[16xitem.enderPearl@0, 10xitem.enderPearl@, 1xtile.air@0]

第一个计数是16和第二个10我想将它们合并在一起并得到一个如下所示的列表:[26xitem.enderPearl@0, 1xtile.air@0], 还有setCount(int)方法,以便可以用来设置新对象的计数。

我尝试了这个(列表叫做堆栈,就像上面的例子一样)

List<ItemStack> newStacks = Lists.newArrayList();
for (int index = 0; index < stacks.size(); index++) {
    ItemStack stack = stacks.get(index);
    ListIterator<ItemStack> iterator = stacks.listIterator();
    while (iterator.hasNext()) {
        int index1 = iterator.nextIndex();
        ItemStack itemStack = iterator.next();
        if (index != index1 && stack.getUnlocalizedName().equals(itemStack.getUnlocalizedName())) {
            newStacks.removeIf(itemStack1 -> itemStack1.getUnlocalizedName().equals(itemStack.getUnlocalizedName()));
            stack.setCount(stack.getCount() + itemStack.getCount());
        }
    }
    newStacks.add(stack);
}

但我得到[36xitem.enderPearl@0, 1xtile.air@0]

1 个答案:

答案 0 :(得分:0)

想出来,正确的方法是通过复制itemstack(复制方法从当前ItemStack复制所有数据并返回一个新数据)从列表中删除,因为它在列表本身中发生了变化,因此在第二次迭代时它将第二个对象中的10添加到第一个对象,在第一次迭代时将其更改为26。

List<ItemStack> newStacks = Lists.newArrayList();
    for (int index = 0; index < stacks.size(); index++) {
        ItemStack stack = stacks.get(index).copy();
        ListIterator<ItemStack> iterator = stacks.listIterator();
        while (iterator.hasNext()) {
            int index1 = iterator.nextIndex();
            ItemStack itemStack = iterator.next();
            if (index != index1 && stack.getUnlocalizedName().equals(itemStack.getUnlocalizedName())) {
                newStacks.removeIf(itemStack1 -> itemStack1.getUnlocalizedName().equals(itemStack.getUnlocalizedName()));
                stack.grow(itemStack.getCount()); // the equivalent of stack.setCount(stack.getCount() + itemStack.getCount());
            }
        }
    }
newStacks.add(stack);
}
相关问题