首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用hashmap对相似项进行分组

使用hashmap对相似项进行分组
EN

Stack Overflow用户
提问于 2013-10-08 11:30:33
回答 5查看 202关注 0票数 0

我有一个这样的输入

代码语言:javascript
运行
复制
0    [0.327097, 0.326998, 0.0]
0    [1.056364, 0.601873, 0.0]
0    [1.273154, 1.656441, 0.0]
1    [1.48469, 0.095074, 0.0]
1    [1.061504, -0.768175, 1.0]

我需要将它们排序为

代码语言:javascript
运行
复制
0 :  [ [0.327097, 0.326998, 0.0] ,[1.056364, 0.601873, 0.0], [1.273154, 1.656441, 0.0]]
1 :  [ [1.48469, 0.095074, 0.0], [1.061504, -0.768175, 1.0]]

我确实喜欢这样..。

但是我没有得到重复的output.my输出。

你能帮帮我吗?

代码语言:javascript
运行
复制
Map<String, Collection<String>> groupMap = new HashMap<String, Collection<String>>();
                   String[] subparts = finalline.split("\\[");    

                  String groupKey;
                  String value;

                  if (subparts.length == 1) {                                 
                      groupKey = null;
                      value = subparts[0];
                  }
                  else    if (subparts.length == 2) {                         
                      groupKey = subparts[0];
                      value = subparts[1];
                  }
                      else {
                      throw new IllegalArgumentException("Can not parse string");
                  }

                  Collection<String> groupContents = groupMap.get(groupKey);     
                  if (groupContents == null) {                                    
                      groupMap.put(groupKey, groupContents = new ArrayList<String>());
                  }
                  groupContents.add(value);                                    

                }
EN

回答 5

Stack Overflow用户

发布于 2013-10-08 11:34:33

groupMap映射的值是另一个集合,因此可以在外部循环中遍历该集合,如下所示

代码语言:javascript
运行
复制
Map<String, Collection<String>> groupMap = new HashMap<String, Collection<String>>();
for(String key : groupMap.keySet()){
    System.out.println("Key: " + key);
    Collection<String> values =  groupMap.get(key);
    for(String value : values){
        System.out.println("value: " + value);
    }
}
票数 2
EN

Stack Overflow用户

发布于 2013-10-08 11:36:31

代码语言:javascript
运行
复制
Map<String, Collection<String>> groupMap = new HashMap<String, Collection<String>>();
for (String s : groupMap.keySet()) {
   for (String s1 : groupMap.get(s)) {
       System.out.println(s1);
   }
}

集合中的集合只表示嵌套循环--就像2D数组一样。

票数 1
EN

Stack Overflow用户

发布于 2013-10-08 11:37:16

循环遍历Map中的条目的最有效方法如下:

代码语言:javascript
运行
复制
Map<String, Collection<String>> groupMap = new HashMap<String, Collection<String>>();
for (Map.Entry<String, Collection<String>> entry : map.entrySet()) {
    System.out.println("Key: "+entry.getKey());
    for (String val : values) {
        System.out.printlnln("Value: "+entry.getValue());
    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19238595

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档