组合对象的两个ArrayList并在组合时有条件地改变对象的值

时间:2016-09-08 12:24:02

标签: java arraylist

我想结合两个相似类型的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);
    }
}

我有两个这类对象的arrylist就像这样

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

我想以这种方式组合它们,所以combined的输出将是这样的

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

我看过其他问题,但无法找到有效的方法。 提前致谢

2 个答案:

答案 0 :(得分: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)

如果您不关心元素的排序,则使用 DateTime localTime = DateTime.Now; string timeString24Hour = localTime.ToString("dd-MM-yyyy HH:mm:ss", CultureInfo.InvariantCulture) ; 可能更有意义。 如果您向Set添加元素,则会使用Set对元素进行测试,并且不会添加重复项。

但是,如果您需要对列表有一些排序感,那么您可以使用removeAll(Collection<?> c)方法删除列表中的重复元素。

喜欢这个......

.equals