Are you storing the IP addresses as String
instances? This is likely the case, because String
are sorted lexicographically, meaning "10" < "2"
.
If you want to sort them numerically, there are several ways:
- Instead of putting them into a
List<String>
, put them into a List<Integer>
- or maybe even a
SortedSet<Integer>
- Keep the
List<String>
, but provide a custom comparator that convert the String
to numerical value for comparison
- may not be most efficient, but works without major changes to existing infrastructure
- although perhaps major changes isn't a bad idea to begin with...
Here's an example that combines a bit of both into one:
import java.util.*;
public class IPSorter {
static Long toNumeric(String ip) {
Scanner sc = new Scanner(ip).useDelimiter("\\.");
return
(sc.nextLong() << 24) +
(sc.nextLong() << 16) +
(sc.nextLong() << 8) +
(sc.nextLong());
}
public static void main(String[] args) {
Comparator<String> ipComparator = new Comparator<String>() {
@Override public int compare(String ip1, String ip2) {
return toNumeric(ip1).compareTo(toNumeric(ip2));
}
};
SortedSet<String> ips = new TreeSet<String>(ipComparator);
ips.addAll(Arrays.asList(
"192.168.0.1", "192.168.0.250", "192.168.0.9", "9.9.9.9"
));
System.out.println(ips);
// "[9.9.9.9, 192.168.0.1, 192.168.0.9, 192.168.0.250]"
}
}
API links