字符串排序
方法1:直接用数组排序
public class StringSort {
public static void main(String[] args) {
String[] strings = {"abc123", "abc+1234", "ababab--1"};
// 对每个字符串计算字母字符个数和数字字符个数,并按照字母数字比和字符串本身大小排序
Arrays.sort(strings, (s1, s2) -> {
int alphaCount1 = 0, numericCount1 = 0;
for (char c : s1.toCharArray()) {
if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z') alphaCount1++;
else if (c >= '0' && c <= '9') numericCount1++;
}
double ratio1 = numericCount1 == 0 ? Double.MAX_VALUE : (double) alphaCount1 / numericCount1;
int alphaCount2 = 0, numericCount2 = 0;
for (char c : s2.toCharArray()) {
if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z') alphaCount2++;
else if (c >= '0' && c <= '9') numericCount2++;
}
double ratio2 = numericCount2 == 0 ? Double.MAX_VALUE : (double) alphaCount2 / numericCount2;
if (ratio1 < ratio2) return 1;
else if (ratio1 > ratio2) return -1;
else return s2.compareTo(s1); // 按照降序排列
});
// 输出排序后的结果
System.out.println(Arrays.toString(strings));
}
}
方法二:用Collections进行排序
import java.util.*;
import java.text.*;
public class Main{
public static void main(String[] args){
String[] strings = {"abc123","abc+1234","abcabab--1"};
HashMap<String,Double> map = new HashMap<>();
for(int i=0; i<strings.length; i++){
map.put(strings[i],getFun(strings[i]));
}
System.out.println(map);
Set<String> set = map.keySet();
ArrayList<String> list = new ArrayList<>();
for(String str:set){
list.add(str);
}
Collections.sort(list,(str1,str2)->{
// return map.get(str1)==map.get(str2) ? str1.compareTo(str2) : map.get(str2) - map.get(str1);
if(map.get(str1)==map.get(str2)){
return str1.compareTo(str2);
}
if(map.get(str2)>map.get(str1)){
return 1;
}else{
return -1;
}
});
System.out.println(list);
}
public static double getFun(String line){
int charNum=0;
int digNum = 0;
for(int i=0; i<line.length();i++){
if(line.charAt(i)>='0'&&line.charAt(i)<='9'){
digNum++;
}else{
charNum++;
}
}
return 1.0*charNum/digNum;
}
}
作者:静默虚空
欢迎任何形式的转载,但请务必注明出处。
限于本人水平,如果文章和代码有表述不当之处,还请不吝赐教。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)