I am loading some values in JSON and I would like to control and delete the duplicates:
public void loadEventos(){
SharedPreferences prefs = getSharedPreferences(getString(R.string.gamedata), Context.MODE_PRIVATE);
String data=prefs.getString("eventos","");
eventos.clear();
if(!data.isEmpty()) {
try {
JSONObject jo = new JSONObject(data);
if(jo.has("eventos")){
JSONArray ja=jo.getJSONArray("eventos");
for (int i = 0; i < ja.length(); i++) {
if (!ja.getString(i).isEmpty()) {
Evento ev=new Evento(ja.getString(i));
Log.d(GLOBALES.TAG,"eventosString="+eventos.get(i).toString());
Log.d(GLOBALES.TAG,"eventosArray="+ja.getString(i));
if(ev.getFinalizacion()>System.currentTimeMillis()) {
eventos.add(ev);
}
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Since events must necessarily be a List, the best thing you can do is determine if the element you are going to insert exists among the elements of the list before inserting it. The fastest way to search for elements within a fairly large list is a binary search. But you have the problem that the lists must be sorted. Sorting wastes time in execution. So you should ask yourself a question:
Can
eventos
you get to have many records?If the answer is yes. The most optimal thing is to sort the list once, Then, look for the new record in your sorted list each time you go to make an insert and if it is not there, insert it in an ordered way. This way the list is always sorted.
Sort the list: You can sort a list using the function
Collections.sort(List<T>)
. Now the Event class must implementComparable
. It is an interface in which a method is implemented, in that method you indicate how to order the list. To show an example:Once the interface is implemented you could call the method on the first line of the method:
Search for the element: You can search for the element by calling the following method binarySearch(List> list, T key) which returns the position at which the element is found or -(correct insertion point) if it is not found
Orderly insertion: Finally, it only remains to insert the element in an orderly manner. Since it
binarySearch
returns the position in negative in which the element should be minus one. Just save that integer and subtract 1 from it:Example
I leave you an example with strings:
If the answer is No, you can just override the equals method of the Event
Override the
equals()
Event method to identify which element is equal to which other.Create the if: