Is there any method to sort this? Or do I just need to split it and use a loop to compare? Input
123.4.245.23
104.244.253.29
1.198.3.93
32.183.93.40
104.30.2
public class SortIP
{
public static String getFormattedIP(String ip)
{
String arg[] = new String[4];
arg = (ip).split("\\.");
int i=0;
while(i<=3)
{
if(arg[i].length()==1)
{
arg[i]="00"+arg[i];
}
else if(arg[i].length()==2)
{
arg[i]="0"+arg[i];
}
i++;
}
return arg[0]+arg[1]+arg[2]+arg[3];
}
public static ArrayList sortedList(Object[] obj,String order)
{
if(order.equalsIgnoreCase("Ascending"))
{
Arrays.sort(obj, new Comparator() {
public int compare(Object o1, Object o2) {
return ((Map.Entry) o1).getValue()
.compareTo(((Map.Entry) o2).getValue());
}
});
}
else
{
Arrays.sort(obj, new Comparator() {
public int compare(Object o1, Object o2) {
return ((Map.Entry) o2).getValue()
.compareTo(((Map.Entry) o1).getValue());
}
});
}
int counter=0;
ArrayList key = new ArrayList();
//int key[] = new int[ipRange.size()];
for (Object e : obj) {
key.add(((Map.Entry) e).getKey());
//key[counter++]=((Map.Entry) e).getKey();
System.out.println(((Map.Entry) e).getKey() + " : " + ((Map.Entry) e).getValue());
}
return key;
}
public static void main(String[] args)
{
Map ipRange= new TreeMap();
Map formatedIpRange= new TreeMap();
ipRange.put(1, "10.1.4.100");
ipRange.put(2, "1.10.400.10");
ipRange.put(3, "196.0.14.15");
ipRange.put(4, "196.70.5.1");
ipRange.put(5, "196.70.7.3");
ipRange.put(6, "153.70.7.0");
for(int j=1;j<=ipRange.size();j++)
{
formatedIpRange.put(j, Long.parseLong(getFormattedIP(ipRange.get(j))));
}
Object[] a = formatedIpRange.entrySet().toArray();
ArrayList key = sortedList(a,"descending");
System.out.println("ordered list ");
for (Integer integer : key)
{
System.out.println(ipRange.get(integer));
}
}
}