What is the most efficient way to search a list of objects and also increment one of its variables? Also addData() function call 10000 time and in this list have max 30 diff-diff key with increment variable .
Thanks,
public void addData(List<DataWise> wise ,String name)
{
if(wise!=null)
{
for (DataWise dataWise : wise) {
if(dataWise.getName().equals(name))
{
dataWise.setVisits(1);
return;
}
}
}
DataWise dataWise2=new DataWise(name,1);
wise.add(dataWise2);
}
public class DataWise
{
private String name;
private int visits;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getVisits() {
return visits;
}
public void setVisits(int visits) {
this.visits+= visits;
}
}
If it’s guarantteed that the name of each DataWise is unique in the list, use a
HashMap<String, DataWise>, where the String key is the name of the DataWise. This will lead to O(1) instead of O(n):Note that a setter (
setVisits()) should set the visits value to the value of the argument. Incrementing the number of visits is really counter-intuitive. This is why I used anincrementVisitsmethod, which is much clearer.