如何使用值作为列表或数组对HashMap中的键进行分组 [英] How to group the keys from a HashMap using values as a List or an Array

查看:61
本文介绍了如何使用值作为列表或数组对HashMap中的键进行分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了一个Map,它使用字符串作为键,使用Integer作为值。因此,它类似于citiesWithCodes

出于测试目的,到目前为止,我已经手动将这些值放入Hashmap中。它们是:

Map<String, Integer> citiesWithCodes = new HashMap<String, Integer>();
        citiesWithCodes.put("Berlin", 49);
        citiesWithCodes.put("Frankfurt", 49);
        citiesWithCodes.put("Hamburg", 49);
        citiesWithCodes.put("Cologne", 49);
        citiesWithCodes.put("Salzburg", 43);
        citiesWithCodes.put("Vienna", 43);
        citiesWithCodes.put("Zurich", 41);
        citiesWithCodes.put("Bern", 41);
        citiesWithCodes.put("Interlaken", 41);

我想根据城市代码以列表或数组格式获取城市。因此,例如,对于值43,它应该返回类似{43=[Vienna, Salzburg]}的内容。

我尝试了以下方法。这绝对是一种肮脏的方法,而且没有给出正确的结果。

   public static Map<Integer, List<String>> codeCities(Map<String, Integer> citiesWithCodes){
       Map<Integer, List<String>> segList = new HashMap<Integer, List<String>>();
       List<String> city;
       Iterator<Entry<String, Integer>> i = citiesWithCodes.entrySet().iterator();
       while (i.hasNext()) {
           city = new ArrayList<String>();
           Entry<String, Integer> next = i.next();
           i.remove();
           city.add(next.getKey());
           for (Entry<String, Integer> e : citiesWithCodes.entrySet()) {
               if(e.getValue().equals(next.getValue())){
                   city.add(e.getKey());
                   citiesWithCodes.remove(e);
               }
           }
           System.out.println(city);
           segList.put(next.getValue(), city);
       }
       return segList;
   }
我得到的输出是:{49=[Cologne], 41=[Interlaken], 43=[Salzburg]} 谁能告诉我,取得成果的正确方法是什么?

PS:我知道使用Multimap是可能的。但我们仅限于使用Java Collection Framework,而不能同时使用Java 8。

推荐答案

如果您的作用域仅限于Java7,请尝试更改以下代码:

 Map<Integer, List<String>> segList = new HashMap<Integer, List<String>>();
 Iterator<Entry<String, Integer>> i = citiesWithCodes.entrySet().iterator();
            while (i.hasNext()) {
                  Entry<String, Integer> next = i.next();
                  if (segList.get(next.getValue()) != null) {
                       List<String> city= segList.get(next.getValue());
                       city.add(next.getKey());
                       segList.put(next.getValue(), city);
                  }else{
                        List<String> city=new ArrayList<String>();
                        city.add(next.getKey());
                        segList.put(next.getValue(), city);

                  }
            }

输出:

{49=[法兰克福,柏林,汉堡,科隆],41=[伯尔尼,苏黎世, 因特拉肯],43=[维也纳,萨尔茨堡]}

这篇关于如何使用值作为列表或数组对HashMap中的键进行分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆