Mounir Elfassi - 1 year ago 53

Java Question

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.

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

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);
}
```

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**