基于hashMap中的值拆分hashMap的字符串

时间:2016-04-05 22:27:46

标签: java string list hashmap

我如何通过一个字符串的值拆分hashMap?例如,按键分割下面的hashMap表:attribute1值:" 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", };

有什么方法可以通过删除具有相应值索引的键的所有值来实现此目的吗?从我所学到的知识来看,由于价值观在地图中没有索引,因此可以使用?

1 个答案:

答案 0 :(得分:0)

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

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;
}