在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. 仅从全局对象中获取 msg ;

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



波斯汪
浏览 106回答 2
2回答

慕勒3428872

所以,我做了这样的事情,我认为它可以满足你的要求。基本上,我所做的是以下内容。我将所有全局值添加到映射中,并在局部值的下一次迭代中检查 id 是否存在,然后更改isFavor.public static void main(String[] args) throws ParseException {&nbsp; &nbsp; List<Info> local = new ArrayList<>();&nbsp; &nbsp; local.add(new Info(1,"msg1",false));&nbsp; &nbsp; local.add(new Info(2,"msgTwo",false));&nbsp; &nbsp; local.add(new Info(3,"msg3",true));&nbsp; &nbsp; local.add(new Info(4,"msg4",true));&nbsp; &nbsp; List<Info> global = new ArrayList<>();&nbsp; &nbsp; global.add(new Info(1,"msg1",false));&nbsp; &nbsp; global.add(new Info(2,"msg2",false));&nbsp; &nbsp; global.add(new Info(3,"msg3",false));&nbsp; &nbsp; global.add(new Info(4,"msg5",true));&nbsp; &nbsp; Map<Integer, Info> map = new HashMap<>();&nbsp; &nbsp; for (Info info : global) {&nbsp; &nbsp; &nbsp; &nbsp; if (!map.containsKey(info.id)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; map.put(info.id, info);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; for (Info info : local) {&nbsp; &nbsp; &nbsp; &nbsp; if (map.containsKey(info.id)){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; map.get(info.id).isFavor = info.isFavor;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; System.out.println(map.values());}

鸿蒙传说

public Info [] merge(Info [] localArray, Info [] globalArray) {&nbsp; &nbsp; List<Info> resultList = new ArrayList();&nbsp; &nbsp; for(Info infoGlobal : globalArray) {&nbsp; &nbsp; &nbsp; &nbsp; Info infoLocal = findInfo(infoGlobal.getId(), localArray);&nbsp; &nbsp; &nbsp; &nbsp; if( infoLocal != null )&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; infoGlobal.setFavor(infoLocal.isFavor());&nbsp; &nbsp; &nbsp; &nbsp; resultList.add(infoGlobal);&nbsp; &nbsp; }&nbsp; &nbsp; return resultList.toArray();}private Info findInfo(int id, Info [] infoArray) {&nbsp; &nbsp; for(Info info : infoArray)&nbsp; &nbsp; &nbsp; &nbsp; if(info.getId == id)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return info ;&nbsp; &nbsp;return null ;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java