【问题标题】:Using hash maps to create a table in Java使用哈希映射在 Java 中创建表
【发布时间】:2016-04-03 22:35:00
【问题描述】:

我正在尝试创建一个程序,让您可以将任何数据放入表中,并且您可以执行计算一列、行中有多少字等功能。使用HashMap 是最好的方法关于这个?

如果没有,你能推荐什么?

目前我正在努力计算每个字母,并且每次给 a = 8bc = 0 时,每个值都加 1

public  void main(String[] args){
    map.put("0", "a");
    map.put("1", "b");
    map.put("2", "c");
    map.put("3", "a");
    map.put("4", "b");
    map.put("5", "a");
    map.put("6", "b");
    map.put("7", "c");

    for(Map.Entry ent : map.entrySet()){
        if(map.containsValue("a")){
        x++;}

        else if(map.containsValue("b")){
        y++;}

        else if(map.containsValue("c")){
        z++;}
    }

    System.out.println("a = " + x);
    System.out.println("b = " + y);
    System.out.println("c = " + z);

【问题讨论】:

    标签: java hashmap hashtable


    【解决方案1】:

    使用 HashMap 是解决此问题的最佳方式吗?

    HashMap 是一个不错的方法,但是您在示例中使用它的方式存在缺陷,因为您不能简单地计算一个键出现了多少次。

    所以我建议使用HashMap<String, List<Integer>>List<Integer> 跟踪行索引:

        HashMap<String, List<Integer>> map = new HashMap<String, List<Integer>>();
        String[] strs = {"a", "b", "c", "a", "b", "a", "b", "c"};
    
        for(int i = 0 ; i < strs.length ; i++) {
            String s = strs[i];
            if(map.containsKey(s)) {
                map.get(s).add(i);
            } else {
                map.put(s, Arrays.asList(new Integer[]{i}));
            }
        }
    
        System.out.println("a = " + map.get("a").size());
        System.out.println("b = " + map.get("b").size());
        System.out.println("c = " + map.get("c").size());
    

    【讨论】:

    • 如何保持一行的数字?
    • @AndrewTobilko 代替Integer,您可以使用List&lt;Integer&gt; 作为行索引,list.size() 将是出现次数
    【解决方案2】:

    如果您可以使用来自第三方的数据结构,您可能需要使用Guava's ArrayListMultimap

    Multimap<Character, Integer> map = ArrayListMultimap.create();
    String str = "abcababc";
    
    for (int i = 0 ; i < str.length() ; i++) {
        map.put(str.charAt(i), i);
    }
    
    for (Character c : map.keySet()) {
        System.out.println(String.format(%c = %d", c, map.get(c).size());
    }
    

    【讨论】:

      猜你喜欢
      • 2018-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-01
      • 2014-05-06
      • 1970-01-01
      • 2023-04-08
      • 1970-01-01
      相关资源
      最近更新 更多