我想結合兩個相似類型的數組列表。但是有條件地,如果一個對象的屬性匹配,則將其他對象的屬性合併爲一個。組合兩個對象的ArrayList,並在合併時有條件地改變對象的值
這裏是我的模型類
public class SampleModel {
int number;
String name;
boolean isSimilar;
public SampleModel(int number, String name, boolean isSimilar) {
this.number = number;
this.name = name;
this.isSimilar = isSimilar;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isSimilar() {
return isSimilar;
}
public void setSimilar(boolean similar) {
isSimilar = similar;
}
@Override
public boolean equals(Object o) {
boolean result = false;
if (this == o){
result = true;
}
if (o == null || getClass() != o.getClass()){
result = false;
}
SampleModel that = (SampleModel) o;
if(name.matches("(.*)"+that.name+"(.*)")){
result = true;
}
if(name.matches("(.*)"+that.name)){
result = true;
}
if(name.matches(that.name+"(.*)")){
result = true;
}
if(name.contains(that.name)){
result= true;
}
return result;
}
@Override
public int hashCode() {
return Objects.hash(name);
}
}
我有這種類型的對象的篩選
ArrayList<SampleModel> sampleModels_one = new ArrayList<SampleModel>();
ArrayList<SampleModel> sampleModels_two = new ArrayList<SampleModel>();
ArrayList<SampleModel> combined = new ArrayList<SampleModel>();
sampleModels_one.add(new SampleModel(1,"a",true));
sampleModels_one.add(new SampleModel(1,"b",true));
sampleModels_one.add(new SampleModel(1,"c",true));
sampleModels_two.add(new SampleModel(1,"b",false));
sampleModels_two.add(new SampleModel(2,"c",false));
sampleModels_two.add(new SampleModel(3,"d",false));
sampleModels_two.add(new SampleModel(3,"e",false));
我想他們在這樣的方式組合兩個arrylist,所以combined
輸出,將是這樣的
SampleModel(1,"a",true)
SampleModel(1,"b",true)
SampleModel(1,"c",true)
SampleModel(1,"d",false)
SampleModel(1,"e",false)
我看了其他SO問題,但無法找到這是一個有效的方法。 在此先感謝
謝謝,你剛纔救了我的一天 –