解析arraylist中的交叉值

时间:2014-07-22 03:51:35

标签: java algorithm

public class IDS{
    public String id;
    public long startTime;
    public long endTime;
}

List<IDS> existingIDS = new ArrayList<IDS>();
List<IDS> newIDSToWrite = new ArrayList<IDS>();

我想将newIDSToWrite值与existingIDS值合并,如果发生冲突,newIDSToWrite值优先。

existingIDS的值为(id1,4,7) (id2,10,14) (id3,16,21)

newIDSToWrite的值为(id4,1,5) (id5,8,9) (id6,12,15) (id7,18,20)

如果上面newIDSToWriteexistingIDS合并,结果应该像(id4,1,5) (id1,5,7) (id5,8,9) (id2,10,12) (id6,12,15) (id3,16,18) (id7,18,20) (id3,20,21)

这是最好的方法吗?

3 个答案:

答案 0 :(得分:2)

您可以使用方法List.retainAll()

existingIDS.retainAll(newIDSToWrite);

链接到doc

<强>更新
dasblinkenlight的好评:在类ID中你应该覆盖hash()equals()方法以实现正确的行为(使用相同值创建的两个ID应该相等,即使它们没有指向到堆中的同一个对象。)

答案 1 :(得分:0)

您也可以使用apache commons ListUtils

ListUtils.union(existingIDS ,newIDSToWrite );

您可以找到文档here

对于问题的第二部分,您可以使用与之前提出的问题相同的逻辑,但稍作修改

delete intersecting values in an arraylist

  1. (1,3)(2,4)(5,6)
  2. curmax = -inf
  3. curmax = 3
  4. 2&lt; 3 - 将第一和第二标记为“不良”。 curmax = 4
  5. 将值2更新为(3 + 1)
  6. 5&gt; 4 - 什么都不做。 curmax = 6。
  7. (5,6) - 是唯一的好片段。

答案 2 :(得分:0)

我推荐这样的东西(请注意,由于我快速编写,因此可能无法直接编译)。此代码基本上使您的类更加面向对象,并要求使用有效的id初始化对象。如上所述,您必须实现hashCode()和equals()才能正确比较对象并检查对象是否包含在集合中(我通常让eclipse在选择字段时为我生成这些函数):

public class IDS {
    private String id;
    private long startTime;
    private long endTime;
    public IDS(String id){
      if(id == null) throw new Exception("RAII failure: IDS requires non-null ID");
      this.id = id;
    }
    // id - getter
    // startTime, endTime - getters/setters

    public boolean equals(IDS otherId){
      if(otherId == null) return false;
      return otherId.getId().equals(getId());
    }
}

List<IDS> existingIDS = new ArrayList<IDS>(); 
List<IDS> newIDSToWrite = new ArrayList<IDS>();

Set<IDS> mergedIds = new HashSet<IDS>(newIDSToWrite);
for(IDS id : existingIDS){
  if(!mergedIds.contains(id)) mergedIds.add(id);
}