Mounir Elfassi Mounir Elfassi - 3 months ago 11
Java Question

Get the minimum value and its index with a for loop

How can I get the minimum value in a for loop plus its index:?

Update: This is what I tried after using @Sakalya 's answer

LatLng myLatLang = new LatLng(myLocation.getLatitude(),myLocation.getLongitude());

double minval = -1.0;
int minIndex = 0;

for (int i = 0; i < stationsCoord.size(); i++) {

double distance = CalculationByDistance(myLatLang,stationsCoord.get(i));

if(distance < minval){
minval = distance;
minIndex = i;
}

Log.i("distance " , String.valueOf(distance));

System.out.println("min=" +minval+ "index="+minIndex);

}

//i'm looking for the min value of 'distance' + the index 'i'


I always get this:
System.out: min=-1.0index=0


Thank you in advance.

Answer

First you can set a min variable to 1000000 and then iterate the list to find min value as below:

LatLng myLatLang = new LatLng(myLocation.getLatitude(), myLocation.getLongitude());

double minval = 1000000000000.0;
int minIndex = 0;

for (int i = 0; i < stationsCoord.size(); i++) {

    double distance = CalculationByDistance(myLatLang,stationsCoord.get(i));

    if (distance < minval) {
      minval = distance;
      minIndex = i;
    }

    Log.i("distance " , String.valueOf(distance));

    System.out.println("min=" +minval+ "index="+minIndex);

}