gpt4 book ai didi

java - java中的合并数组

转载 作者:行者123 更新时间:2023-12-02 03:29:31 26 4
gpt4 key购买 nike

我需要按对象的 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)}

最佳答案

所以,我做了类似的事情,我认为这符合你的要求。基本上,我所做的如下。我将所有全局值添加到 map 中,并在本地值的下一次迭代中,检查 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());
}

关于java - java中的合并数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56893187/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com