Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
128 views
in Technique[技术] by (71.8m points)

Sorting by 2 substrings in a string in Java


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to

  1. split the strings
String[] split=string.split(" ");
  1. test if the second substrings are the same
split1[1].equals(split2[1])
  1. if they are the same, compare the days
Integer.parseInt(split1[0])<Integer.parseInt(split2[0]);

If not, compare the month names using an array with the month names or similar.

private static final String[] MONTHS={"Jan","Feb",...};
private int getMonthNumeric(String abbr){
    for(int i=0;i<MONTHS.length();i++){
        if(abbr.equals(MONTHS[i]){
            return i;
        }
    }
    return -1;
}
//in your comparator
getMonthNumeric(split1[1])<getMonthNumeric(split1[1])

A simple comparator (ignoring edge cases) could look like this (using a lambda):

(a,b)->{
    String[] split1=a.split(" ");
    String[] split2=b.split(" ");
    if(split1[1].equals(split2[1])){
        return Integer.parseInt(split1[0])-Integer.parseInt(split2[0]);
    }else{
        return getMonthNumeric(split1[1])-getMonthNumeric(split1[1]);
    }
}

Your code sorting the list could look like the following:

private static final String[] MONTHS={"Jan","Feb",...};
private int getMonthNumeric(String abbr){
    for(int i=0;i<MONTHS.length();i++){
        if(abbr.equals(MONTHS[i]){
            return i;
        }
    }
    return -1;
}
//Where you want to sort the date:
Collections.sort(dates,(a,b)->{
        String[] split1=a.split(" ");
        String[] split2=b.split(" ");
        if(split1[1].equals(split2[1])){
            return Integer.parseInt(split1[0])-Integer.parseInt(split2[0]);
        }else{
            return getMonthNumeric(split1[1])-getMonthNumeric(split1[1]);
        }
    }
);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...