1.重写equals方法,name相同即为相等
2.新建一个List,用来放结果。
3.遍历旧的List,如果新的list中存在名字相同的,则新的List中该元素的count+1. 如果不存在,则放入新的List
示例代码:
//测试类
public class ListTest {
public static void main(String[] args) {
List<ListTestObject> oldList = new ArrayList<>();
//模拟数据
oldList.add(new ListTestObject("jack", 1));
oldList.add(new ListTestObject("jerry", 1));
oldList.add(new ListTestObject("jone", 1));
oldList.add(new ListTestObject("jerry", 1));
oldList.add(new ListTestObject("jone", 1));
List<ListTestObject> newList = new ArrayList<>();
for (ListTestObject testObjOld : oldList) {
// 遍历新的List,看是否存在,存在则count加一,不存在则放入新的List
boolean flag = false;
for (ListTestObject testObjNew : newList) {
if (testObjNew.equals(testObjOld)) {
// 新的List中存在名字相同的,则count+1
testObjNew.setCount(testObjNew.getCount() + 1);
flag = true;
}
}
// 新的List中不存在
if (!flag) {
newList.add(testObjOld);
}
}
System.out.println(newList);
}
}
//实体类
public class ListTestObject {
private String name;
private int count;
//因为示例只用了name,count,另外3个属性先不写。
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public ListTestObject(String name, int count) {
super();
this.name = name;
this.count = count;
}
@Override
public boolean equals(Object obj) {
ListTestObject testObj;
try {
testObj = (ListTestObject) obj;
} catch (Exception e) {
//类不同,直接返回false
return false;
}
if(testObj.getName().equals(this.getName())){
return true;
}
return false;
}
@Override
public String toString() {
return "ListTestObject [name=" + name + ", count=" + count + "]";
}
}
引用 极光舞者 [极光舞者](https://ask.csdn.net/questions/341593)