【问题标题】:Splitting a hashMap based on values in it's string根据字符串中的值拆分 hashMap
【发布时间】:2016-04-05 22:27:45
【问题描述】:

我将如何通过一个字符串的值来拆分 hashMap?例如下面的 hashMap 表按 key 拆分:attribute1 value:"a".

    public Map<String, List> table = new HashMap<String, List>();

        String[] attribute1 = {"a", "a", "b", "c", "c"};
        String[] attribute2 = {"car", "car", "car", "train", "bus"};
        String[] attribute3 = {"yes", "no", "no", "no", "yes"};

这样它会给出:

        String[] attribute1 = {"a", "a"};
        String[] attribute2 = {"car", "car"};
        String[] attribute3 = {"yes", "no", };

有什么方法可以通过删除具有相应值索引的键的所有值来做到这一点?根据我了解到的情况,您不能因为这些值在 has maps 中没有索引?

【问题讨论】:

  • 问题不明确。 this.popItem 和这个问题有什么关系?
  • 对不起,这不是,只是包含在我的代码中的使用方式
  • 为什么要使用前缀this?它由 JVM 自动包含,
  • 问题不清楚。 HashMap 目前的内容是什么?
  • 对不起,如果我含糊不清,很难说出这个问题,我想这就是为什么我自己很难回答这个问题,因为我不太明白。我基本上希望能够通过其中一个列表,选择一个值,例如“a”并删除所有没有“a”的列。这更有意义吗?

标签: java string list hashmap


【解决方案1】:

只需找到正确的列,然后循环遍历表中的所有条目并提取正确的列:

public static Map<String,List> filterMap(Map<String,List> table, String key, String filter) {
   Map<String,List> m = new HashMap<String,List>();
   List l = table.get(key);
   if (l != null) {
      List<Integer> cols = new List<Integer>();
      for (int i = 0; i < l.size(); i++) {
         if ((filter == null && l.get(i) == null) || (filter != null && filter.equals((String)l.get(i)))) {
            cols.add(new Integer(i));
         }
      }
      // for each entry in table
      //    extract the items saved in cols and add it to m
   }
   return m;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-12
    • 1970-01-01
    • 1970-01-01
    • 2019-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多