There are two sub-problems.
1- Comparing two huge arraylists
2- Sorting elements of arraylist based on the values of its object to achieve (1).
I have an ArrayList of objects of a class. i.e.
Class X
{
double x;
double y;
int sortVal;
}
ArrayList<X> alX = new ArrayList<X>(); //size = 10,000
ArrayList<Integer> myValue = new ArrayList<Integer>(); //size = 15
I want to check if myValue is present in sortVal.
X ob = new X();
for(i=0;i<myValue.size();i++)
{
for(j=0;j<alX.size();j++)
{
ob = alX.get(j)
**if (myValues.get(i) == ob.sortVal)**
}
}
As the size of the arraylist ‘alX’ is huge, it takes high computation time.
I thought the better way would be to sort the elemets of ArrayList alX based on the values of sortVal of Class X. By sorting, once sortVal is greater than myValue, I can break from the loop.
1) how can I sort the elements of arraylist alX based on the value ‘sortVal’.
2) Is there a better approach, than sorting the arraylist, to compare the two values. i.e. (myValues.get(i) == alX.ob.sortVal)
[edit] Consider the values being,
ArrayList<X>:
x : 1,1,1,2,3,5,4,5
y : 2,4,6,4,4,6,2,1
sortVal: 10,20,30,10,10,20,30
ArrayList<Integer>:
myValue: 10,20,30
You could construct a
Map<Integer, X>if sortVal values are unique orMap<Integer, Lists<X>>if they are not. This has a time complexity of O(n) instead or O(n * log n) which is the cost of doing a sort.EDIT: This builds a MultiMap of keys and the set of objects for that key in one pass.