题解 | #成绩排序#
成绩排序
https://www.nowcoder.com/practice/8e400fd9905747e4acc2aeed7240978b
Java数据结构-HashMap+流式编程
题目分析
输入数据:一组序列(名字,成绩)
操作目标:将数据排序 从低到高/从高到低,相等数据按照原序列排列
本题数据量不多,但是需要将字符串和数据对应起来
使用一个map将成绩和名字链表对应起来
然后使用一个数据存储对应的成绩,sort之后遍历输出
代码细节
- Scanner的使用:Scanner的nextInt()和nextLine()方法不能混合使用,如果需要读取整型和字符串,可以使用Integer.parseInt()方法进行转换;
- 流式编程复习 .mapToInt()是一个抽象的方法,可以填写具体的实现,sort()方法如果需要自定义Comparator,那么需要进行装箱的操作,toArray()可以将流转化为数组;
- Arrays.sort()方法默认为从低到高排序。
练习过程代码有所不完善和不优化,敬请指正(o゚v゚)ノ
代码
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// 开始输入数据
int nums = Integer.parseInt(scanner.nextLine());
int manner = Integer.parseInt(scanner.nextLine());
int[] scores = new int[nums];
Map<Integer, List<String>> map = new HashMap<>();
// 开始遍历数据
for(int i=0;i<nums;i++){
String[] info = scanner.nextLine().split(" ");
int score= Integer.parseInt(info[1]);
scores[i] = score;
String name = info[0];
List<String> list = map.getOrDefault(score,new ArrayList<>());
list.add(name);
map.put(score,list);
}
if(manner==1) Arrays.sort(scores);
else scores = Arrays.stream(scores).boxed().sorted((n1,n2)->n2-n1).mapToInt(n->{return (int)n;}).toArray();
// 开始遍历数组输出
for(int score : scores){
List<String> list = map.get(score);
System.out.println(list.get(0)+" "+ score);
list.remove(0);
}
}
}