具有动态列的数据结构

时间:2020-06-08 14:13:57

标签: java

在以下情况下,其中3个数组是分层的-List#3持有List#2的子代,而List#2持有List#1的子代-我想要一个包含List#1,List#2的最终列表,List#3-每个列表都由(id,child_id)组成,因此List#1和List#2之间的链接为:List1.child_id = List2.id,依此类推:List2.child_id = List3.id

  1. 键值列表#1:

    [(id=1,child_id=5), (id=2,child_id=6), (id=3,child_id=7), ...]
    
  2. 键值列表2:

    [(id=5,child_id=10), (id=6,child_id=11), (id=7,child_id=12), ...]
    
  3. 键值列表3:

    [(id=10,child_id=34), (id=11,child_id=35), (id=12,child_id=36), ...]
    

我需要一个数据集,该数据集将基于id = child_id的3个数据相结合,如下所示:

[(id=1, child_id_1=5, child_id_2=10,child_id_3=34), (id=2, child_id_1=6, 
child_id_2=11,child_id_3=35), (id=3, child_id_1=7, child_id_2=12,child_id_3=36), ...]

如何用Java实现呢?而且,列表的数量是动态的,这意味着> 3个列表。

2 个答案:

答案 0 :(得分:0)

这将为您工作。对于下面的每个输入列表,逻辑将运行。

List<Map<String,Integer>> mapList = new ArrayList<Map<String,Integer>>();
    for(int i = 0; i < list.size(); i++) {
        Map<String,Integer> tempMap = new HashMap<String,Integer>();
        tempMap.put("id",list.get(i).getId());
        for(int j = 0; j < list.size(); j++) {
            tempMap.put("child_id_"+list.get(j).getId(),list.get(j).getChild_id());
        }
        mapList.add(tempMap);
    }
    System.out.println(mapList);
}

这是输出。 [{child_id_1 = 10,child_id_2 = 11,id = 1},{child_id_1 = 10,child_id_2 = 11,id = 2}]

答案 1 :(得分:0)

我创建了一个Class Data来保存所需的值,请参考以下代码,

for (let i = 0; i < totalInheritors.length; i++) {
  let memOpt = document.createElement('option');
  memOpt.value = totalInheritors[i];
  memOpt.text = totalInheritors[i];
  memOpt.classList.add('member-name')
  mem.appendChild(memOpt);
}

输出

    public static void main(String[] args) throws Exception {
        Map<Integer, Integer> map1 = new HashMap<Integer, Integer>();
        map1.put(1, 5);
        map1.put(2, 6);
        map1.put(3, 7);

        Map<Integer, Integer> map2 = new HashMap<Integer, Integer>();
        map2.put(5, 10);
        map2.put(6, 11);
        map2.put(7, 12);

        Map<Integer, Integer> map3 = new HashMap<Integer, Integer>();
        map3.put(10, 34);
        map3.put(11, 35);
        map3.put(12, 36);

        List<Data> datas = new ArrayList<Data>();
        for (Map.Entry<Integer, Integer> entry : map1.entrySet()) {
            Data data = new Data();
            data.key = entry.getKey();
            int value = entry.getValue();
            data.col_1 = value;
            data.col_2 = map2.get(value);
            data.col_3 = map3.get(data.col_2);
            datas.add(data);
        }
        System.out.println(datas);
    }
}

class Data{
    int key;
    int col_1;
    int col_2;
    int col_3;
    @Override
    public String toString() {
        return "Data [key=" + key + ", child_1=" + col_1 + ", child_2=" + col_2 + ", child_3=" + col_3 + "]\n";
    }   
}