【问题标题】:java hashmap valuesjava hashmap 值
【发布时间】:2012-05-24 04:22:25
【问题描述】:

我的 hashmap 包含一个键,它是客户的名字,值是所有书籍的评分。我必须计算给定书名的平均评分。

如何访问哈希图中的所有值(评级)?有没有办法做到这一点?

这是我的一段代码:

/** 
 * calculate the average rating by all customers for a named book
 * only count positive or negative ratings, not 0 (unrated)
 * if the booktitle is not found or their are no ratings then
 * return NO_AVERAGE
 * @param booktitle String to be rated
 * @return double the average of all ratings for this book
 */
public double averageRating(String booktitle) 
{ 
    numberOfRatingsPerCustomer/total
}

【问题讨论】:

  • 哈希映射将键映射到单个值。你能澄清一下你的数据结构是什么吗?
  • 所有 Java Maps(包括 HashMaps)都有一个 method named values(),它返回一个值的集合。
  • 好的,我正在尝试创建一个包含所有书单的数据结构,然后客户对他/她名下的书进行评分。你能告诉我如何计算平均评分
  • @AkanshaDahiya:平均评分=总评分/评分数。
  • 我不知道如何获得评分数,它不会只是 hashmap 的大小

标签: java hashmap average


【解决方案1】:

您需要从 HashMap 中获取 keySet。然后遍历 keySet 并从 HashMap 中获取值。

【讨论】:

  • 这家伙是对的。迭代键集并使用每个键检索值(这将是您的 ArrayList)并使用它。关于这些内容的更多帮助,您应该阅读 Java API。
  • 迭代 entrySet() 比迭代 keySet() 并计算每个键的哈希值以逐个查找值更有效。
【解决方案2】:

你的问题毫无意义。

您不能拥有包含customerNamehisRatingOfBook 的地图,并在其中搜索bookTitle。您需要采用以下 1 种方式之一:

1) 在Book 类中创建方法public double averageRating(),并保持在那里,作为字段,评级为customerNamehisRatingOfBook 的映射

2) 使用你的方法:

public double averageRating(String booktitle) 
{ 
    numberOfRatingsPerCustomer/total
}

但是让你的地图更复杂,它将包含customer,以及它的rating(由书名+费率组成)

【讨论】:

    【解决方案3】:

    你去拿下面的这些代码,它会帮助你找到你的评级问题 我已经做到了找出班级中学生的平均成绩

    import java.util.*;
    
    public class QueQue {
    
    public static float getAverage(HashMap<String, ArrayList<Integer>> hm, String name) {
        ArrayList<Integer> scores;
        scores = hm.get(name);
        if (scores == null) {
            System.out.println("NOT found");
        }
    
        int sum = 0;
        for (int x : scores) {
            sum += x;
        }
        return (float) sum / scores.size();
    }
    public static void main(String[] args) {
        HashMap<String, ArrayList<Integer>> hm = new HashMap<>();
        hm.put("Peter", new ArrayList<>());
        hm.get("Peter").add(10);
        hm.get("Peter").add(10);
        hm.get("Peter").add(10);
    
        hm.put("Nancy", new ArrayList<>());
        hm.get("Nancy").add(7);
        hm.get("Nancy").add(8);
        hm.get("Nancy").add(8);
    
        hm.put("Lily", new ArrayList<>());
        hm.get("Lily").add(9);
        hm.get("Lily").add(9);
        hm.get("Lily").add(8);
    
        System.out.println("Find the average of the Peter");
        float num = getAverage(hm, "Peter");
    
    }
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-10
      • 2016-05-01
      • 2015-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多