java - 在不同列表之间移动属性

标签 java algorithm list collections

我只想在两个不同列表之间移动一个属性:

我有一份狗的 list List<Dog>

public class Dog{
    private int id;
    private String name;
    private String newValue;
}

在第一个列表中,我没有 newValue 属性的值。

第二个列表是List<DogProp>

public class DogProp{
    private int id;
    private String newValue;
}

在第二个列表中,我有 newValue 属性的值。

我想要的是从 List<DogProp> 移动 newValue 属性至 List<Dog>. 在这种情况下,列表可以有不同数量的元素和不同的元素,这意味着列表的大小可以不同,元素也可以。

我想要的操作是这样的:

  • 如果 id 属性在 List<DogProp>匹配 List<Dog> 中的 id 属性,我想从 List<DogProp> 移动 newValue 属性至 List<Dog>

我知道我可以创建某种算法来做到这一点,但我想知道在某些 google 项目或 apache commons 项目中是否有现有的解决方案来避免 重新发明了轮子。

更新: 由于这似乎是题外话,因为我要求一个库来执行此操作,现在我想知道使用工具或算法实现此目的的最佳方法。

谢谢。

最佳答案

我和@Alan 一样,也不确定是否有内置解决方案,但也同意 Alan 的观点,即编写自己的算法来实现这一技巧应该相当简单。 - 遍历两个列表,创建两个将 id 映射到 Dog/DogProp 对象的字典。然后循环遍历 dogProps,如果存在与任何 Dog 对象匹配的 ID,则执行替换。

代码如下:

static void transferDogProps(List<Dog> dogList, List<DogProp> dogPropList){
    Dictionary<String,Dog> dogDictionary = new Dictionary<String,Dog>();
    Dictionary<String,DogProp> dogPropDictionary = new Dictionary<String,DogProp>();
    foreach(Dog dog in dogList) dogDictionary.Add(dog.getId(),dog);
    foreach(Dog dogProp in dogPropList) dogPropDictionary.Add(dogProp.getId(),dogProp);
    foreach(String id in dogPropList.Keys){
        if(dogDictionary.ContainsKey[id]){
            Dog matchingDog = dogDictionary[id];
            DogProp matchingDogProp = dogPropDictionary[id];
            matchingDog.setNewValue(matchingDogProp.getNewValue());
        }
    }
}

关于java - 在不同列表之间移动属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22649050/

相关文章:

list - 如何将函数映射到三重嵌套列表并保持三重嵌套列表完整?

python - 重新启动以循环迭代列表python3

java - 无效的转义字符

JavaWebStart 以及图像和文件等资源

java - 从第三方获取 JSON 数据并绕过 SOP

algorithm - 将矩阵重写为规则

c++ - 如何找到转换光线的位置以避免在 Bullet 中发生碰撞?

java - Java 中的 IoT 模块 GET 请求

algorithm - 你如何完美地散列一个可能的 unicode 字符与一个 32 位整数的联合?

list - Haskell - 增量失败