Java中队数字和字符串混合list的比较和排序

比较器

import java.util.Comparator;

import org.apache.commons.lang.StringUtils;


/**
 * @author NevenChen
 *Comparator for numeric
 */
public class LUX_NumericComparator_mxJPO implements Comparator<String>{
	
	private String sortType = "ascending";
	
	public LUX_NumericComparator_mxJPO () throws Exception{
    }
	public LUX_NumericComparator_mxJPO (String sortType) throws Exception{
        if(StringUtils.isBlank(sortType)){
        	this.sortType = sortType;
        }
    }

    @Override
    public int compare(String string1,String string2){
        int diff = 0;
        int dirMult = 1;
        Double long1  = null,long2 = null;
        boolean isStr1Number = true;
        boolean isStr2Number = true;     

        // If the direction is not ascending, then set the
        // multiplier to -1.  Otherwise, set the multiplier to 1.
		if (!"ascending".equals(sortType)) {
			dirMult = -1;
		} else {
			dirMult = 1;
		}
		
		if (StringUtils.isBlank(string1) && StringUtils.isBlank(string2)) {
			// If both values are null, then they are the same.
			diff = 0;
		} else if (StringUtils.isBlank(string1)) {
			// If the first value is null, then it is first.
			diff = -1;
		} else if (StringUtils.isBlank(string2)) {
			// If the second value is null, then it is first.
			diff = 1;
		}else{
			// If both values are non-null, then compare
			// the data differently depending on the data type.
			// Check if string1 is number
			try {
				long1 = Double.parseDouble(string1);
			} catch (Exception ex) {
				isStr1Number = false;
			}

			// Check if string2 is number
			try {
				long2 = Double.parseDouble(string2);
			} catch (Exception ex) {
				isStr2Number = false;
			}

			// If one of them is number and other string
			// then consider number to be larger then string
			if (isStr1Number != isStr2Number) {
				if (isStr1Number)
					diff = -1;
				else
					diff = 1;
			} else {
				if (isStr1Number) {
					// Compare the long values of the strings.
					diff = long1.compareTo(long2);
				} else {
					// Compare the string values.
					diff = string1.compareToIgnoreCase(string2);
				}
			}
		}

        return diff * dirMult ;
            
    }
	
}

 测试代码:

@Test
	public static void test_sortStringNumericValues() throws Exception{
		List<String> sl = new ArrayList<String>();
		sl.add("77");
		sl.add("88.2");
		sl.add("88.3");
		sl.add("-88.3");
		sl.add("-88.2");
		sl.add("-88.3");
		sl.add("0");
		sl.add("76");
		sl.add("-76");
		sl.add("?");
		sl.add("N/A");
		sl.add("-");
		sl.add("zzzzz");
		sl.add("aaa");
		Collections.sort(sl, new LUX_NumericComparator_mxJPO("ascending"));
		for(Object obj : sl){
			System.out.println(obj);
		}
	}

 输出结果:

-88.3
-88.3
-88.2
-76
0
76
77
88.2
88.3
-
?
aaa
N/A
zzzzz

 

你可能感兴趣的:(java)