Java如何对存储英尺英寸格式身高的字符串ArrayList实现降序排序
Java身高字符串降序排序实现方案
你原本直接使用String.compareTo的写法仅能处理英尺位数完全相同的场景,一旦出现英尺为两位数的身高(比如10'2")就会出现排序错误。你提到的拆分字符串转总英寸数比较的思路是正确且高效的,没有算法层面更优的实现,仅存在代码写法层面的优化:
优化实现1:Java 8及以上通用写法
首先修正你初始代码的笔误:Collections.sort的入参写错为players,实际应为待排序的heights列表,优化后的lambda写法如下:
ArrayList<String> heights = new ArrayList<>(); // 填入测试数据 heights.add("5'11\""); heights.add("6'11\""); heights.add("4'2\""); heights.sort((o1, o2) -> { // 计算第一个身高的总英寸数 String[] parts1 = o1.split("'"); int feet1 = Integer.parseInt(parts1[0]); int inch1 = Integer.parseInt(parts1[1].replace("\"", "")); int total1 = feet1 * 12 + inch1; // 计算第二个身高的总英寸数 String[] parts2 = o2.split("'"); int feet2 = Integer.parseInt(parts2[0]); int inch2 = Integer.parseInt(parts2[1].replace("\"", "")); int total2 = feet2 * 12 + inch2; // 降序排列用total2比较total1,升序则调换顺序 return Integer.compare(total2, total1); });
优化实现2:Java 12+ 高可读性写法
可以用Comparator.comparingInt直接提取排序键,逻辑更直观易维护:
// 定义提取总英寸数的公共函数,可复用 ToIntFunction<String> getTotalInch = heightStr -> { String[] parts = heightStr.split("'"); int feet = Integer.parseInt(parts[0]); int inch = Integer.parseInt(parts[1].replace("\"", "")); return feet * 12 + inch; }; // 直接调用reversed()实现降序,语义清晰 heights.sort(Comparator.comparingInt(getTotalInch).reversed());
大数据量场景优化
如果待排序的列表数据量在百万级以上,可以提前缓存每个身高对应的总英寸数,避免排序过程中重复拆分计算同一个字符串的数值,降低性能损耗:
// 提前缓存所有身高的总英寸数 Map<String, Integer> heightCache = new HashMap<>(); for (String h : heights) { if (heightCache.containsKey(h)) continue; String[] parts = h.split("'"); int total = Integer.parseInt(parts[0]) * 12 + Integer.parseInt(parts[1].replace("\"", "")); heightCache.put(h, total); } // 排序时直接读取缓存值比较 heights.sort((o1, o2) -> Integer.compare(heightCache.get(o2), heightCache.get(o1)));
内容的提问来源于stack exchange,提问作者awawawaw
相关产品推荐
相关产品推荐

