list集合取相同数据求平均分 5C

List> list = new ArrayList>();
Map map = new HashMap();
map.put("name", "语文");
map.put("score", 80);
list.add(map);

    Map<String, Object> map2 = new HashMap<String, Object>();
    map2.put("name", "数学");
    map2.put("score", 76);
    list.add(map2);

    Map<String, Object> map3 = new HashMap<String, Object>();
    map3.put("name", "语文");
    map3.put("score", 90);
    list.add(map3);

    Map<String, Object> map4 = new HashMap<String, Object>();
    map4.put("name", "数学");
    map4.put("score", 80);
    list.add(map4);

    Map<String, Object> map5 = new HashMap<String, Object>();
    map5.put("name", "英语");
    map5.put("score", 89);
    list.add(map5);

需求是求相同科目的平均分,不同科目就不算平局分,打印出来,谢谢了

12个回答

double [] myArray = new double[10];
double sum = 0;
double avg = 0;
var result = from r in list group r by r.name into g where g.Count() > 1 select g;
foreach (var item in result)
{
myArray[i] = Convert.ToDouble(item);
sum += myArray[i];

}
avg = sum / result.Count;
Console.WriteLine(avg);

AnxLuc
AnxLuc 回复sky_2018: 求解 from r in list group r by r.name into g where g.Count() > 1 select g?
2 年多之前 回复
sky_2018
sky_2018 高手,学习了
2 年多之前 回复
xiaocainiaoIng
xiaocainiaoIng Java 代码里可以这样写?
2 年多之前 回复

String kemu = "";
for (int i = 0; i<list.size(); i++) {
String name = (String) list.get(i).get("name");
Integer score = (Integer) list.get(i).get("score");
int count = 1;
for (int j =0; j<list.size(); j++) {
if (list.get(j).get("name") == name) {
if (i != j) {
count++ ;
score = score + (Integer)list.get(j).get("score");
}
}
}
if (kemu.indexOf(name)== -1) {
System.out.println(name+":平均分是:"+ score/count);
}
kemu = kemu + name + "%%%";
}

1.先将集合进行分组(分组字段)
2.在判断分组的数量是否大于 0
3.大于0,则有重复的数据

简单粗暴的直接一个循环求解不就行了?

伪代码(python风格, 总是只是表达下思路)

map

key: str, subject name, such as 语文

value: tuple, (total_score, count), such as (80, 1), (160, 2)

map = {}
for item in list:
if map.has_key(item[0]):
values = map[item[0]]
values[0] += item[1]
values[1] += 1
else:
values = (item[1], 1)
map[item[0]] = values

for r in map:
print "subject:", r
values = map[r]
# average = total_scroe / count
print "average:", 1.0 * values[0] / values[1]

print "OK, I have implemented it with python, you can implement yours referred to it."

//set集合去重,不打乱顺序
public static void main(String[] args){
List list = new ArrayList();
list.add("aaa");
list.add("bbb");
list.add("aaa");
list.add("aba");
list.add("aaa");

     Set set = new  HashSet(); 
     List newList = new  ArrayList(); 
     for (String cd:list) {
        if(set.add(cd)){
            newList.add(cd);
        }
    }
     System.out.println( "去重后的集合: " + newList); 
  }

 //遍历后判断赋给另一个list集合
 public static void main(String[] args){
     List<String> list  =   new  ArrayList<String>(); 
     list.add("aaa");
     list.add("bbb");
     list.add("aaa");
     list.add("aba");
     list.add("aaa");

     List<String> newList = new  ArrayList<String>(); 
     for (String cd:list) {
        if(!newList.contains(cd)){
            newList.add(cd);
        }
    }
     System.out.println( "去重后的集合: " + newList); 
  }

//set去重
public static void main(String[] args){
     List<String> list  =   new  ArrayList<String>(); 
     list.add("aaa");
     list.add("bbb");
     list.add("aaa");
     list.add("aba");
     list.add("aaa");

    Set set = new  HashSet(); 
     List newList = new  ArrayList(); 
     set.addAll(list);
     newList.addAll(set);

     System.out.println( "去重后的集合: " + newList); 
 }

    //set去重(缩减为一行)
    public static void main(String[] args){
         List<String> list  =   new  ArrayList<String>(); 
         list.add("aaa");
         list.add("bbb");
         list.add("aaa");
         list.add("aba");
         list.add("aaa");

         List newList = new ArrayList(new HashSet(list)); 

         System.out.println( "去重后的集合: " + newList); 
     }

建一个Map map ; key = "科目" (语文、数学等) value二维数据 array[0]总分 array[1]数量

在listadd之前 给map设值 按照key进行 总分增加 数量增加

listadd完成后 根据map获取每科的平均数

a718089112
a718089112 回复a718089112: 一个数组 数组 数组 打字老错啊。。。 心态崩了
2 年多之前 回复
a718089112
a718089112 一个数据 2个元素 打字错了 Map<String,Double[]> map ; Double数组2个元素
2 年多之前 回复
xiaocainiaoIng
xiaocainiaoIng 二维数据这个地方不是 很明白
2 年多之前 回复

for(int i=0;i<list.size();i++){
String name =(String) list.get(i).get("name");
Integer count=0;
for(int j=0;j<list.size();j++){
if(name.equals(list.get(j).get("name"))){
//计算有相同的
count+=Integer.valueOf(String.valueOf(list.get(j).get("score")));
}
}
//计算没有相同的
if(count==0){
count+=Integer.valueOf(String.valueOf(list.get(i).get("score")));
}
//避免重复计算
list.remove(i);
System.out.println(name+"--"+count);
}

// 把各科目分组保存
Map<String, List<Integer>> resultMap = new HashMap<String, List<Integer>>(); // 最终要的结果
for (Map<String, Object> item : list) {
    String name = (String) item.get("name");
    Integer score = (Integer) item.get("score");

        if(resultMap.containsKey(name)){
                resultMap.get(name).add(score);
        }else{
                List<Integer> i = new ArrayList<Integer>();
                i.add(score);
                resultMap.put(name,i);
        }
}

// 最终要的结果
Map<String, Double> svgMap = new HashMap<String, Double>(); 
// 计算平均分
for (String key : resultMap.keySet()) {
    List<Integer> scoreList = resultMap.get(key);
    Double totleScore = 0D;
    for (Integer object : scoreList) {
        totleScore += object;
    }
    svgMap.put(key, totleScore/scoreList.size());
}
System.out.println("各科目与其平均分保存在svgMap里");

public static void main(String[] args) {
getAvgScoreOfCourse()
}

static void getAvgScoreOfCourse() {

    List<CourseScore> dataList = initData()
    Map<String, CCount> map = new HashMap<>()
    for (CourseScore c : dataList) {
        CCount d = map.get(c.name)
        if (!d) {
            d=new CCount(name: c.name,num: 0,scores: 0)
            map.put(c.name,d)
        }
        d.num++
        d.scores += c.score
    }


    for (CCount c : map.values()) {
        c.avg = new BigDecimal(c.scores).divide(new BigDecimal(c.num), 2, BigDecimal.ROUND_HALF_UP)
       println c.name+" 平均分:"+c.avg
    }


}

static List initData() {
CourseScore c1 = new CourseScore(name: "语文", score: 80)
CourseScore c2 = new CourseScore(name: "数学", score: 76)
CourseScore c3 = new CourseScore(name: "语文", score: 90)
CourseScore c4 = new CourseScore(name: "数学", score: 80)
CourseScore c5 = new CourseScore(name: "英语", score: 89)
List list = new ArrayList()
list.add(c1)
list.add(c2)
list.add(c3)
list.add(c4)
list.add(c5)

    return list
}

    /**
  • 课程,分数 / class CourseScore { String name Integer score } /*
  • 课程,人数,总分数,平均分 */ class CCount { String name Integer num Integer scores String avg }

我这没考虑浮点型数据,你要考虑的话可以把int改为浮点型
public void test() {
List list = new ArrayList();
Map map2 = new HashMap();
map2.put("name", "数学");
map2.put("score", 76);
list.add(map2);

    Map<String, Object> map3 = new HashMap<String, Object>();
    map3.put("name", "语文");
    map3.put("score", 90);
    list.add(map3);

    Map<String, Object> map4 = new HashMap<String, Object>();
    map4.put("name", "数学");
    map4.put("score", 80);
    list.add(map4);

    Map<String, Object> map5 = new HashMap<String, Object>();
    map5.put("name", "英语");
    map5.put("score", 89);
    list.add(map5);
    Map<String, Object> map6 = new HashMap<String, Object>();
    map6.put("name", "英语");
    map6.put("score", 91);
    list.add(map6);
    //key是科目,value是int数组,数组第一位代表当前平均分,第二位个数
    Map<String, int[]> averageMap = new HashMap<>();
    list.forEach(item -> {
        String name = String.valueOf(item.get("name"));
        int[] averageScoreArr = averageMap.get(name);
        int score = Integer.parseInt(String.valueOf(item.get("score")));
        if (averageScoreArr == null) {
            averageScoreArr = new int[]{score, 1};
            averageMap.put(name, averageScoreArr);
        } else {
            int averageScore = averageScoreArr[0];//前一次平均值
            int count = averageScoreArr[1];//出现次数
            averageScoreArr[0] = (averageScore * count + score) / (count + 1);
            averageScoreArr[1] = count + 1;
        }
    });
    //测试结果
    averageMap.forEach((k, v) -> System.out.println(k + "=" + v[0]));

}
共12条数据 1 尾页
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问