合并对象的ArraList,不含公有制,并保留Java中所有对象的所有归档值[已关闭]。


我有两个对象的ArrayList,比如

ArrayList<Record>  dataSetOne;
ArrayList<Record>  dataSetTwo;

其中记录对象的样子

public class Record{
  private String id;
private String name;
private String HomeAdrress;
private String OfficeAdrress;
}

所以,在第一个ArrayList,即dataSetOne中,我将得到与家庭住址相关的记录数据,在第二个ArrayList,即dataSetTwo中,我将得到与办公室地址相关的记录数据。

public class Record{
  id = emp01;
 name = andy;
 HomeAdrress = mexico;
}

在第二个ArrayList中,即dataSetTwo中,我将得到与办公室地址相关的详细记录数据。

public class Record{
   id = emp01;
   name = andy;
   officeAdrress = california;
}

所以要求是我需要合并这两个数组列表,并结合以id为主的记录,并得到家庭和办公室地址,就像下面这样。

public class Record{
  id = emp01;
   name = andy;
  HomeAdrress = mexico;
   officeAdrress = california;
}

谅谅

解决方案:

import java.util.*;

/* define your IncompleteRecordErr here */
class IncompleteRecordException extends Exception {
    IncompleteRecordException() {    
        super("Your record is incomplete. Vital data missing!");
    }
}

/* */
class Record {
    public int id;
    public String name;
    public String homeAddress;
    public String officeAdrress;
}

public class App {
    public static void main(String[] args) {
        ArrayList<Record> arrList1 = new ArrayList<>();
        ArrayList<Record> arrList2 = new ArrayList<>();
        /* full your arrLists above with elements */

        ArrayList<Record> merged = new ArrayList<>();
        for(int i = 0; i < arrList1.size(); i++) { // supposed both data lists have same len        
            Record r1 = arrList1.get(i);
            Record r2 = arrList2.get(i);
            Record currentRecord = new Record();
            if(r1.id != 0) currentRecord.id = r1.id; // check for not default value
            else if(r2.id != 0) currentRecord.id = r2.id;
            //else throw new IncompleteRecordException();

            if(r1.name != null) currentRecord.name = r1.name;
            else if(r2.name != null) currentRecord.name = r2.name;
            //else throw new IncompleteRecordException();

            if(r1.homeAddress != null) currentRecord.homeAddress = r1.homeAddress;
            else if(r2.homeAddress != null) currentRecord.homeAddress = r2.homeAddress;
            //else throw new IncompleteRecordException();

            if(r1.officeAdrress != null) currentRecord.officeAdrress = r1.officeAdrress;
            else if(r2.officeAdrress != null) currentRecord.officeAdrress = r2.officeAdrress;
            //else throw new IncompleteRecordException();

            merged.add(currentRecord);
        }
    // now, "merged" should contain your merged data
    }
}

给TA打赏
共{{data.count}}人
人已打赏
未分类

Gradle在Android Studio中为Dependent Spinner构建错误

2022-10-10 9:21:26

未分类

各种numpy随机函数之间的区别

2022-10-10 9:21:28

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索