用Java语言解决下列问题:“班里5个同学身高分别为(唐剑 175, 何峰 173, 王铭友 174 ,冯琳 172 , 左志远 179)请按照身高从矮到高输出人名!”
时间: 2024-02-29 22:52:26 浏览: 29
好的,您可以使用Java中的Map和List来实现这个问题,具体代码如下:
```java
import java.util.*;
public class HeightSort {
public static void main(String[] args) {
Map<String, Integer> heights = new HashMap<>();
heights.put("唐剑", 175);
heights.put("何峰", 173);
heights.put("王铭友", 174);
heights.put("冯琳", 172);
heights.put("左志远", 179);
List<Map.Entry<String, Integer>> heightList = new ArrayList<>(heights.entrySet());
// 使用Collections.sort对list中的元素按值进行排序
Collections.sort(heightList, new Comparator<Map.Entry<String, Integer>>() {
@Override
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
return o1.getValue().compareTo(o2.getValue());
}
});
// 输出排序后的结果
for (Map.Entry<String, Integer> entry : heightList) {
System.out.println(entry.getKey());
}
}
}
```
输出结果为:
```
冯琳
何峰
王铭友
唐剑
左志远
```
这里利用了HashMap来存储每个同学的姓名和身高,然后使用ArrayList将Map中的元素转化为List,再使用Collections.sort对List中的元素按值进行排序,最后按照顺序输出排序后的姓名。