本文共 1499 字,大约阅读时间需要 4 分钟。
需要对存在ArrayList<String>中的ipAddress进行排序,下面做法是达不到效果的:
List ipAddress = new ArrayList ();ipAddress.add("10.1.2.1");ipAddress.add("10.121.76.89");ipAddress.add("10.121.76.132");ipAddress.add("10.121.76.89");Collections.sort(ipAddress);
因为其是按照字符串的标准进行排序,而不是我们需要以基数排序得到的结果,下面就用TreeMap来进行简单的处理:
package com.iqiyi.miaoyun; import java.util.*;/** * Created by niuliguo on 2016/4/11. */public class SortIpAddress { public List结果是令人满意的。sortIpAddress(List list){ Map treeMap = new TreeMap (); for(String ip : list){ String[] str = ip.split("\\."); double key = Double.parseDouble(str[0]) * 1000000 + Double.parseDouble(str[1])*1000 + Double.parseDouble(str[2]) + Double.parseDouble(str[3])*0.001 ; treeMap.put(key , ip); } List ret = new ArrayList (); for( Iterator it = treeMap.keySet().iterator();it.hasNext(); ){ double key = it.next().doubleValue(); String value = treeMap.get(key); ret.add(value); } return ret; } public static void main(String[] args){ List list = new ArrayList (); list.add("10.121.76.92"); list.add("10.121.76.89"); list.add("10.121.76.88"); list.add("10.121.76.132"); list.add("10.121.76.131"); SortIpAddress s = new SortIpAddress(); List ipList = new ArrayList (); ipList = s.sortIpAddress(list); System.out.println(ipList); }}
Author:忆之独秀
Email:leaguenew@qq.com
注明出处:
转载地址:http://epnpf.baihongyu.com/