在两个数组列表之间映射数据

时间:2019-04-11 07:53:43

标签: java android

我有数据:

Item: {String name,String count}

List<Item> listA =[{"a",10},{"b",10},{"c",10},{"d",10},{"e",10},{"f",10}]

List<Item> listB =[{"b",1},{"d",3},{"f",4},{"h",5}]

我希望将数据从listB映射到listA,所以我使用了代码:

for (int i = 0; i < listB.size(); i++) {
   Item item= listB.get(i); // get element in listB
   for (int j = 0; j < listA.size(); j++) {
     if (item.getName().equals(listA.get(j).getName())) {
        listA.get(j).setCount(item.getCount());
     }
   }
}

我的结果:

listA =[{"a",10},{"b",1},{"c",10},{"d",3},{"e",10},{"f",4}]

我的代码正常工作,但我想做得更好。因为它将复制listA中的项目。我怎样才能做得更好?请帮我。非常感谢。

2 个答案:

答案 0 :(得分:1)

我不确定您的Java版本, 但是,如果您使用的版本高于Java 8,您可以在下面尝试此代码吗?

// Map is useful to remove duplicate data,
// so we will convert the list type to map.
Map<String, Integer> mapA = listA.stream()
    .collect(Collectors.toMap(Item::getName, Item::getCount));
Map<String, Integer> mapB = listB.stream()
    .collect(Collectors.toMap(Item::getName, Item::getCount));

// Let's put the data from mapA to mapB
mapB.entrySet().stream()
        .filter(entry -> mapA.containsKey(entry.getKey()))
        .forEach(entry -> mapA.put(entry.getKey(), entry.getValue()));

// Your expected result is list type, like below,
// [{"a": 10},{"b": 1},{"c": 10},{"d": 3},{"e": 10},{"f": 4}]
// convert it to list again!
List<Item> list = mapA.entrySet().stream()
    .map(o -> new Item(o.getKey(), o.getValue())).collect(Collectors.toList());

答案 1 :(得分:0)

尝试创建List而不是HashMap。然后,遍历mapB的条目 并更新mapA。它将自动替换地图中存在的键的值,并生成不存在的条目。

示例代码:

Map<String, Integer> mapA = createMapA() , mapB = createMapB();
mapB.entrySet().foreach(entry -> mapA.put(entry.getKey(), entry.getValue());

lambda代码样式是Java8,但是如果您使用Java7,通常的想法是不变的。