题目:
List list = Arrays.asList(new String[]{“1,张三,50”, “2,李四,80”, “3,王五,40”, “4,张三,90”, “5,王五,70”});
要求:
1.统计列表里的平均分
2.按照平均分进行升序排序
输出结果:
代码:
package com.xu.test;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
public class test {
public static void main(String[] args) {
List<String> list = Arrays.asList(new String[]{"1,张三,50", "2,李四,80", "3,王五,40", "4,张三,90", "5,王五,70"});
HashMap<String,Double> h1 = new HashMap<>(); //分数
HashMap<String,Integer> h2 = new HashMap<>(); //次数
list.forEach(s->{
String[] split = s.split(",");
if(h1.containsKey(split[1])){
h1.put(split[1],h1.get(split[1])+ Double.valueOf(split[2]));
h2.put(split[1],h2.get(split[1])+1);
}else{
h1.put(split[1],Double.valueOf(split[2]));
h2.put(split[1],1);
}
});
h1.forEach((key,value)->{
if(h2.get(key)>1){
Double avg_score = h1.get(key)/h2.get(key);
h1.put(key,avg_score);
}
});
//成绩升序 使用了e1.compareTo(e2) e1-e2 >0 则e1比e2大,所以e1往后放
h1.entrySet().stream().sorted((e1,e2)-> e1.getValue().compareTo(e2.getValue())).forEach(v1 -> {
System.out.println(v1.getKey() +" " + v1.getValue());
});
//成绩降序
// h1.entrySet().stream().sorted((e1,e2)-> e2.getValue().compareTo(e1.getValue())).forEach(v1 -> {
// System.out.println(v1.getKey() +" " + v1.getValue());
// });
}
}