Search My Blog

Wednesday, November 30, 2011

Removing blank spaces from a String in Java

sText= sText.replaceAll("\\s+", "");


Reference -
http://www.mkyong.com/java/how-to-remove-whitespace-between-string-java/

Monday, November 28, 2011

using Comparator to sort a List in JAVA

Sorting a List based on one of its attributes is achieved by using the Comparator interface.

For example,

public class EmpSortByName implements Comparator{

public int compare(Employee o1, Employee o2) {
return o1.getName().compareTo(o2.getName());
}
}

import java.util.*;

public class TestEmployeeSort {

public static void main(String[] args) {

List coll = Util.getEmployees();
//Collections.sort(coll);
//use Comparator implementation
Collections.sort(coll, new EmpSortByName());
printList(coll);
}

private static void printList(List list) {
System.out.println("EmpId\tName\tAge");
for (Employee e: list) {
System.out.println(e.getEmpId() + "\t" + e.getName() + "\t" + e.getAge());
}
}
}

This sorts the list based of employee names.

Calculate distance between 2 geo points

Given the latitude and longitude of 2 points, we can find the distance between then using the Haversine formula.

The Java function to do the same is given below :


public static double getDistance(double lat1, double lon1, double lat2, double lon2)
{
int R = 6371; // km
double dLat = Math.toRadians(lat2-lat1);
double dLon = Math.toRadians(lon2-lon1);
double lat1mod = Math.toRadians(lat1);
double lat2mod = Math.toRadians(lat2);

double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1mod) * Math.cos(lat2mod);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
double d = R * c;

return d;
}

Sunday, November 20, 2011

auto shutdown Windows machine

shutdown /s /t seconds

/s - shutdown, there are other options like /r - restart
/t seconds - specifies time in seconds, after which system will be shutdown