2016-09-08 54 views
1

我想結合兩個相似類型的數組列表。但是有條件地,如果一個對象的屬性匹配,則將其他對象的屬性合併爲一個。組合兩個對象的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問題,但無法找到這是一個有效的方法。 在此先感謝

回答

1

你可以設置這樣做。(可使用linkedhashset維持秩序)

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

謝謝,你剛纔救了我的一天 –

1

如果你不關心元素的順序,它可能會更有意義改爲使用Set。 如果您將元素添加到Set,則元素將使用.equals進行測試,並且不會添加重複項。

但是,如果您需要對列表進行排序,您可以使用removeAll(Collection<?> c)方法刪除列表中的重複元素。

就像這個...

ArrayList<SampleModel> combined = new ArrayList<SampleModel>(); combined.addAll(sampleModels_one); combined.removeAll(sampleModels_two); combined.addAll(sampleModels_two);