Minwu Yu Minwu Yu -4 years ago 133
Java Question

Java how to sort a list of IP Address

I want to sort a list of IP address in ascending order, what is the easiest way to achieve that?

For example I have these IP Address in a

List
:

import java.util.ArrayList;
import java.util.List;

/**
*
* @author myu
*/
public class SortListProject {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
List addressList = new ArrayList();
addressList.add("192.168.0.5");
addressList.add("192.168.0.1");
addressList.add("192.168.25.1");
addressList.add("192.168.10.21");
addressList.add("192.168.77.1");

System.out.println(addressList);
}

}


I would like to sort the list with the following output:

{192.168.0.1, 192.168.0.5, 192.168.10.21, 192.168.25.1, 192.168.77.1}

Answer Source

You are using raw-types. Please don't do that. Next, you'll need to parse the String representation to get int values from the four octets in the IP (or 192.168.100.1 will come before 192.168.2.1). You can pass a custom Comparator to Collections.sort. Assuming you are using Java 8+, they might look something like

List<String> addressList = new ArrayList<>(Arrays.asList("192.168.0.5", // 
        "192.168.0.1", "192.168.25.1", "192.168.10.21", "192.168.77.1"));
Collections.sort(addressList, (a, b) -> {
    int[] aOct = Arrays.stream(a.split("\\.")).mapToInt(Integer::parseInt).toArray();
    int[] bOct = Arrays.stream(b.split("\\.")).mapToInt(Integer::parseInt).toArray();
    int r = 0;
    for (int i = 0; i < aOct.length && i < bOct.length; i++) {
        r = Integer.compare(aOct[i], bOct[i]);
        if (r != 0) {
            return r;
        }
    }
    return r;
});
System.out.println(addressList);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download