Java: complex sorting of prefix strings (ArrayLists)

(No network knowledge is required. This is purely String and Lists).

Let's say I have a function in place that takes a String IPv4 dotted address list and sorts them in ascending order. (Not in alphabetical order, true sorting by long ip format). Let me call it:

public static ArrayList<String> sortListOfIpv4s(ArrayList<String> unsortedIPv4s);

This feature is already working correctly. Given input:

192.168.1.1, 8.8.8.8, 4.5.6.7, 244.244.244.244, 146.144.111.6

It will list:

4.5.6.7, 8.8.8.8, 146.144.111.6, 192.168.1.1, 244.244.244.244

(Let's not discuss whether to change the list in place or return a new list. It just returns a new list. Also, this function cannot be changed for many reasons. )


However, my input list is as follows:

e192.168.1.1, f8.8.8.8, e4.5.6.7, f244.244.244.244, e146.144.111.6

( e f, NOT NECESSARILY alternating) , . :

e4.5.6.7, f8.8.8.8, e146.144.111.6, e192.168.1.1, f244.244.244.244

, , .

:

  • IP- ,
  • ,
  • .

, ? (, , IPv4 String arraylists).

+5
3

. sortListOfIpv4s s.substring(1), s .

sortListOfIpv4s , , Map prefix-free IP -> prefix:

Map<String, String> prefixMap = new HashMap<String, String>();
for (String ip : unsortedIPv4s) {
  prefixMap.put(ip.substring(1), ip.substring(0, 1));
}

Map:

List<String> sortedIPV4s = sortListOfIpv4s(unsortedIPv4s);
for (String ip : sortedIPV4s) {
  String prefix = prefixMap.get(ip);
  String originalIp = prefix + ip;
}
+2

, .

0

:

public class IpComparator implements Comparator<String> {
    @Override
    public int compare(String ipA, String ipB) {
        return doComparison( ipA.substring(1), ipB.substring(1) );
    }
}

:

return Collections.sort(unsortedIPv4s, new IpComparator());
0

All Articles