There is a library available in Java for this. The open-source IPAddress Java library has methods for merging addresses into prefix block subnets. Disclaimer: I am the project manager of the IPAddress library.
The following method "merge" shows the code, relying on the method mergeToPrefixBlocks from the library:
static String[] merge(List<String> strs) {
// convert first to address
IPAddress first = new IPAddressString(strs.get(0)).getAddress();
// convert remaining to address
IPAddress others[] = strs.subList(1, strs.size()).stream().map(str -> new IPAddressString(str).getAddress()).toArray(IPAddress[]::new);
// merge them all
IPAddress[] blocks = first.mergeToPrefixBlocks(others);
// convert back to strings
return Arrays.stream(blocks).map(block -> block.toString()).toArray(String[]::new);
}
The method can be demonstrated with your set of example addresses as shown with the following code:
ArrayList<String> strs = new ArrayList<>();
String firstPref = "1.1.3.";
String secondPref = "1.2.3.";
String thirdPref = "1.3.3.";
for(int i = 0; i <= 255; i++) {
strs.add(firstPref + i);
strs.add(secondPref + i);
}
for(int i = 0; i <= 129; i++) {
strs.add(thirdPref + i);
}
String result[] = merge(strs);
System.out.println("blocks are " + Arrays.asList(result));
The output is:
blocks are [1.3.3.128/31, 1.3.3.0/25, 1.1.3.0/24, 1.2.3.0/24]