在ArrayList中收集相似的对象



我试图创建一个方法,从ArrayList收集所有对象,然后添加类似的对象创建一个名称和数量映射,各种。我希望该方法能够检查类型,名称和hp,如果都是相同的,金额应该增加,也许删除另一个?在此之后,它应该在JavaFX GUI中以可观察列表的形式表示。

本例中的对象是来自模拟的单位,其中照片中表示的8个,应该表示为:类型:InfantryUnit,名称:测试,惠普:10数量:8 .

表示数据的JavaFX GUI

我尝试了几种解决方法,但都无济于事。我认为地图是必要的,但我还没有找到收集和显示单位数量的好方法。同时也检索实际用于模拟的单位数量。

任何帮助都将非常感激!

代码:单位职业是4个子类型的超级职业:步兵,远程,骑兵和指挥官(骑兵的子类型)。

public abstract class Unit implements Bonuses {
private String name;
private int health; //Total health, means the unit can take more damage before dying.
private int attack; //Attack value to decide how much health each attack does.
private int armor; //Defense value to decide resistance to attacks.
private boolean isAlive; //Boolean which tells if a unit is dead or alive.
private int hitsDealt; //Count hits dealt.
private int hitsTaken; //Count hits received.
private String className; //The type of unit, infantry/ranged etc.
private terrain terrain; //Enum terrain from bonus interface.
public Unit(String name, int health, int attack, int armor) {
setName(name);
setHealth(health);
this.attack = attack;
this.armor = armor;
className = getClass().getSimpleName();
hitsDealt = 0;
hitsTaken = 0;
}

Army类只是用来表示这样的单位列表。这就是我想实现上面提到的方法的地方。

public class Army {
private String name;
private List<Unit> units;
private Random randomUnit;
/**
* Constructor of the army class.
*
* @param name Name of army.
*/
public Army(String name) {
this.name = name;
units = new ArrayList<>();
this.randomUnit = new Random();
}

看看org.apache.commons.collections4.MultiSet和它的getCount,它可能符合您的需求。

使用toString()作为键,其中toString()包含unitType、name和health。然后,它检查映射是否包含这样一个键,如果不包含,则添加一个新键。如果存在,则将其添加到与键连接的列表中。

/**
* Method to collect same units into map.
* Used to display amount of units in GUI.
* @return Map of string and a list of units connected to said string.
*/
public Map<String, List<Unit>> getSortedList() {
HashMap<String, List<Unit>> sortedUnits = new HashMap<>();
for (Unit u : units) {
if (sortedUnits.containsKey(u.toString())) {
sortedUnits.get(u.toString()).add(u);
} else {
List<Unit> list = new ArrayList<>();
list.add(u);
sortedUnits.put(u.toString(), list);
}
}
return sortedUnits;
}

此方法的工作原理是连接到toString()键的列表可以使用list.size()进行检查。

最新更新