【问题标题】:Merge two lists on index合并索引上的两个列表
【发布时间】:2015-02-06 14:25:26
【问题描述】:

我有两个包含相同类型对象的列表。每个对象都有一个 int、一个字符串和其他一些东西,其中 int 是它的索引。

这是两个列表都持有的对象:

public class ListElement
{
    private int index;
    private String data;
    private String some;
    private String other;
    private String stuff;

    // gets, sets...

}

我想要的是获取列表 A 的索引和“其他一些东西”,并将其字符串“数据”替换为列表 B 中的字符串。它从列表 B 中获取的字符串应该与列表 A 的索引匹配。我希望这个是可以理解的。

编辑:需要注意的是,对象内部的索引 int 与对象在列表中的实际位置无关。它适用于其他porpuses

【问题讨论】:

  • 如此嵌套的for循环?遍历 ListA,找到 ListB 的匹配元素(如果有)并进行操作。
  • 如果我们希望索引匹配,则不需要嵌套。
  • 这是相对于其包含数组的索引,还是只是一个称为索引的巧合 int 字段?

标签: java arrays list object


【解决方案1】:

更新:您提到 ListElement 的 index 字段与其在其包含列表中的实际位置无关。

您恰好有一个随机名称的字段,您想比较两个列表(加入)。此解决方案使用嵌套循环将一个列表中的每个元素与另一个列表中的每个元素进行比较。

for (int iA = 0; iA < listA.size(); iA++) //iterate over listA
{
    ListElement currentElement = listA.get(iA);
    for (int iB = 0; iB < listB.size(); iB++) //iterate over listB
    {
        ListElement other = listB.get(iB); 
        if (other.index == currentElement.index) //compare the elements
        {
            //do stuff
            currentElement.setData(other.getData()); 
            break; //if only want first match
        }         
    }
}

【讨论】:

    【解决方案2】:

    假设您的两个列表具有相同数量的元素,您可以执行以下操作:

    ListElement sourceElement, destElement;
    for (int i =0; i<list1.size(); i++) {
        sourceElement = list1.get(0);
        destElement = list2.get(0);
        sourceElement.setData(destElement.getData());
        ...
    }
    

    【讨论】:

      【解决方案3】:

      第一个想法可能不是最聪明的,但我稍后会谈到。

      For (ListElement e : ListA) {
        For (ListElement le : ListB) {
          if (e.getIndex() = le.getIndex()) {
            e.setData(le.getData());
          }
        }
      }
      

      所以这是我对你所写内容的第一次尝试,但这可能不是最简单的方法。为了使其更简单和更快,您可以实现接口Comparable 并使用sort,在这种情况下,您可以通过 ListElement 中的索引访问 List 元素(假设您确保索引从 1..n 开始完整)。 我最喜欢的解决方案是使用某种maps 将索引存储为键,并将ListElement 存储为值,那么它只是MapA.get(i).setData(MapB.get(i).getData()) 这是傻瓜证明,只要 MapA 中的每个项目都有一个相应的MapB 中具有相同索引的项目。

      【讨论】:

        【解决方案4】:

        如果您想匹配 ListItem 对象上的 index 字段,请尝试以下操作:

        for (ListItem listItemA : listA) {
            for (ListItem listItemB : listB) {
                if (listItemB.getIndex() == listItemA.getIndex()) {
                    listItemA.setData(listItemB.getData());
                }
            }
        }
        

        如果您有兴趣根据 List 对象中的索引进行匹配,请尝试

        for (int i = 0; i < listA.size(); i++) {
            listA.get(i).setData(listB.get(i).getData());
        }
        

        【讨论】:

          猜你喜欢
          • 2014-06-24
          • 1970-01-01
          • 1970-01-01
          • 2015-10-28
          • 2021-12-26
          • 1970-01-01
          • 1970-01-01
          • 2015-06-03
          • 2017-07-07
          相关资源
          最近更新 更多