首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
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

Stack Overflow用户

发布于 2013-10-08 12:35:50

迭代映射条目的最好、最有效的方法是:

代码语言:javascript
运行
复制
Map<String, Collection<String>> map;
for (Map.Entry<String, Collection<String>> entry : map.entrySet()) {
    System.out.print(entry.getKey()+":");
    for (String str : entry.getValue())
       System.out.println(str);
}

此代码将生成您请求的输出。

请注意,在任何时候都不会查找到密钥。当您迭代项目集时,您可以直接访问(类型化的)键和(类型化的)值。

票数 1
EN
查看全部 5 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19238595

复制
相关文章

相似问题

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