I need your help with some sample code for a situation I could not get free from. I have a simple list of objects. My class is like this:
class MyClass {
String str;
Integer intgr;
}
And the list contains elements like:
[{a1 5}, {b2 3}, {g1 1}, {b5 1}, {c9 11}, {g2 3}, {d1 4}, {b3 19}... ... ...]
I need to check if any element contain the same prefix in string (here suffix is the last single character) then keep that element which have greater value in integer. The expected output from the above example list will be:
[{a1 5}, {c9 11}, {g2 3}, {d1 4}, {b3 19}... ... ...]
Strings will have unique values but could have matches in prefix. I'm not that good in java. So can anybody help me out from this? Here is the code I'm trying but getting IndexOutOfBoundsException. This code has faults, so need some help from you.
Thanks!
int size = list.size();
for (int j = 0; j < size; j++) {
if (list.get(j).str.substring(0, list.get(j).str.length()-1).compareTo(list.get(j+1).str.substring(0, list.get(j+1).str.length()-1)) == 0) {
if (list.get(j).intgr > list.get(j+1).intgr)
list.remove(list.get(j+1));
size--;
else {
list.remove(list.get(j));
j--;
size--;
}
}
}