vjk
vjk

Reputation: 2293

resolve intersecting values in arraylist

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

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

I want to merge the newIDSToWrite values with existingIDS values, with newIDSToWrite values taking precedence if a conflict occurs.

existingIDS has values like this (id1,4,7) (id2,10,14) (id3,16,21)

newIDSToWrite has values like this (id4,1,5) (id5,8,9) (id6,12,15) (id7,18,20)

If the newIDSToWrite above is merged with existingIDS result should be like (id4,1,5) (id1,5,7) (id5,8,9) (id2,10,12) (id6,12,15) (id3,16,18) (id7,18,20) (id3,20,21)

Whats the best way of doing this?

Upvotes: 1

Views: 59

Answers (3)

Blaskovicz
Blaskovicz

Reputation: 6170

I recommend something like this (note that it may not compile directly since I wrote it quickly). This code basically makes your class more object oriented and requires the object be initialized with a valid id. As other mentioned above, you must implement hashCode() and equals() to be able to properly compare objects and check if an object is contained within a collection (I usually have eclipse generate these functions for me upon selecting fields):

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);
}

Upvotes: 0

Nir Alfasi
Nir Alfasi

Reputation: 53565

You can use the method List.retainAll():

existingIDS.retainAll(newIDSToWrite);

Link to the doc.

UPDATE:
Good comment by dasblinkenlight: in class ID you should override hash() and equals() methods in order to achieve a correct behavior (two IDs that are created with the same values should be equal even if they don't point to the same object in the heap).

Upvotes: 2

Aniket Thakur
Aniket Thakur

Reputation: 69035

You can also use apache commons ListUtils

ListUtils.union(existingIDS ,newIDSToWrite );

You can find the documentation here.

For the second part of the question you can use the same logic as the question you has asked earlier but a little modification

delete intersecting values in an arraylist

  1. (1, 3) (2, 4) (5, 6)
  2. curmax = -inf
  3. curmax = 3
  4. 2 < 3 - mark first and second as "bad". curmax = 4
  5. Update value of 2 to (3+1)
  6. 5 > 4 - do nothing. curmax = 6.
  7. (5,6) - is the only good segment.

Upvotes: 0

Related Questions