我想对字母数字值进行排序,就像我的输入是
[a1, b1, c1, aa1, bb1, cc1, d1, e1]
输出应按此顺序-a1,b1,c1,d1,e1,aa1,bb1,cc1
我已经使用了这段代码
public class coll {
public static int comparator(String s1, String s2) {
String[] pt1 = s1.split("((?<=[a-z])(?=[0-9]))|((?<=[0-9])(?=[a-z]))");
String[] pt2 = s2.split("((?<=[a-z])(?=[0-9]))|((?<=[0-9])(?=[a-z]))");
//pt1 and pt2 arrays will have the string split in alphabets and numbers
int i=0;
if(Arrays.equals(pt1, pt2))
return 0;
else{
for(i=0;i<Math.min(pt1.length, pt2.length);i++)
if(!pt1[i].equals(pt2[i])) {
if(!isNumber(pt1[i],pt2[i])) {
if(pt1[i].compareTo(pt2[i])>0)
return 1;
else
return -1;
}
else {
int nu1 = Integer.parseInt(pt1[i]);
int nu2 = Integer.parseInt(pt2[i]);
if(nu1>nu2)
return 1;
else
return -1;
}
}
}
if(pt1.length>i)
return 1;
else
return -1;
}
private static Boolean isNumber(String n1, String n2) {
// TODO Auto-generated method stub
try {
int nu1 = Integer.parseInt(n1);
int nu2 = Integer.parseInt(n2);
return true;
}
catch(Exception x) {
return false;
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] examples = {"a1", "b1", "c1", "aa1", "bb1", "cc1", "d1", "e1"};
List<String> values = new ArrayList<String>(Arrays.asList(examples));
System.out.println(values);
Comparator<String> com = (o1,o2) -> {return comparator(o1,o2);}; //lambda expression
Collections.sort(values,com);
System.out.println(values);
}
}
输出为[a1, aa1, b1, bb1, c1, cc1, d1, e1]
但是,我想要
[a1,b1,c1,d1,e1,aa1,bb1,cc1]
答案 0 :(得分:4)
从外观上看,这就是您想要的:
public static void main(String[] args) {
List<String> a = new ArrayList<>(Arrays.asList("a1", "b1", "c1", "aa1", "bb1", "cc1", "aaa1", "d1", "e1"));
a.sort(Comparator.nullsFirst(Comparator.comparing(String::length).thenComparing(Comparator.naturalOrder())));
System.out.println(a);
}
您首先按长度排序,然后按长度组对字符串进行排序。
输出为:
[a1, b1, c1, d1, e1, aa1, bb1, cc1, aaa1]
Java 7版本:
Collections.sort(a, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
if (o1 == null) return -1;
else if (o2 == null) return 1;
int cmp = Integer.compare(o1.length(), o2.length());
if (cmp != 0) return cmp;
return o1.compareTo(o2);
}
});
以上两个代码示例都是null安全的。
答案 1 :(得分:0)
您也可以先onPageSelected()
然后再public class MainActivity {
private ViewPager mCardsPager;
private ViewPager mIpsPager;
private MyCreditCardsPagerAdapter mCardsAdapter;
private MyInstantPaiementPagerAdapter mIpsAdapter;
private List<PayMethod> mCards;
private List<PayMethod> mIps;
//fill Pager/Adapter/List
@Override
public void onPageSelected(int position) {
if () {//If the page comes from mCardsPager
//do Something with mCards
} else { //else the page comes from mIpsPager
//do Something with mIps
}
}
}
String::length
输出
String::compareToIgnoreCase