合并Java

时间:2019-07-04 19:03:23

标签: java

我需要按对象ID合并数组。我的课程有两个数组(本地和全局):

public class Info {
    private int id;// never change
    private String msg;
    private boolean isFavor;// presents only in local array
// constructor,getters, setters etc 
}

合并规则:

  1. 如果对象不存在于全局数组中,我们不会将其合并;
  2. 仅从全局对象中获取味精;
  3. 如果对象存在于全局数组中,我们将其添加(合并);
  4. 变量“ isFavor”取自本地对象;
  5. 数组未排序;

示例:

local arayList = {Info(1,"msg1",false),Info(2,"msgTwo",false),Info(3,"msg3",true), Info(4,"msg4",true)};

global arayList = {Info(1,"msg1",false),Info(2,"msg2",false),Info(3,"msg3",false),Info(5,"msg5",false)}

result arayList = {Info(1,"msg1",false),Info(2,"msg2",false),Info(3,"msg3",true),Info(5,"msg5",false)}

2 个答案:

答案 0 :(得分:0)

所以,我做了这样的事情,我认为它可以满足您的需求。基本上,我要做的是以下几点。我将所有全局值添加到地图,并在下一次局部值迭代中,检查ID是否存在,并更改isFavor

public static void main(String[] args) throws ParseException {
    List<Info> local = new ArrayList<>();
    local.add(new Info(1,"msg1",false));
    local.add(new Info(2,"msgTwo",false));
    local.add(new Info(3,"msg3",true));
    local.add(new Info(4,"msg4",true));


    List<Info> global = new ArrayList<>();
    global.add(new Info(1,"msg1",false));
    global.add(new Info(2,"msg2",false));
    global.add(new Info(3,"msg3",false));
    global.add(new Info(4,"msg5",true));

    Map<Integer, Info> map = new HashMap<>();

    for (Info info : global) {
        if (!map.containsKey(info.id)) {
            map.put(info.id, info);
        }
    }

    for (Info info : local) {
        if (map.containsKey(info.id)){
            map.get(info.id).isFavor = info.isFavor;
        }
    }

    System.out.println(map.values());
}

答案 1 :(得分:0)

httpWebRequest.Headers.Add(HttpRequestHeader.Authorization, "SomeBasicauthenticationToken");