shuvro shuvro - 3 months ago 16
Java Question

Combine two ArrayList of object and conditionally change value of object while combining

I want to combine two arraylist of similar type . But conditionally , if property of one object match , property of other object than combine them in one .

Here is my model class

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);
}
}


And I have two arrylist of this type of object Like this

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));


I want to combine them in such way , so the output of
combined
, will be like this

SampleModel(1,"a",true)
SampleModel(1,"b",true)
SampleModel(1,"c",true)
SampleModel(1,"d",false)
SampleModel(1,"e",false)


I have looked other SO question but couldn't find a efficient way to this.
Thanks in advance

Answer

You can do it with Set like this.(can use linkedhashset for maintaining order)

        combined.addAll(sampleModels_two);
        combined.addAll(sampleModels_one);

        Set<SampleModel> hs = new LinkedHashSet<>();
        hs.addAll(sampleModels_one);
        hs.addAll(sampleModels_two);
        combined.clear();
        combined.addAll(hs);