Reputation: 2293
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
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
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
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
Upvotes: 0