【问题标题】:Regarding a list and map关于列表和地图
【发布时间】:2012-08-02 09:04:03
【问题描述】:

我正在做一项研究,假设我有以下数组列表

    List list=new ArrayList();
      list.add(1);
      list.add(1);
      list.add(2);
      list.add(3);
      list.add(3);

现在我可以看到列表中重复的元素是 1 和 3 ,现在我想创建 hashMap

Map hm = new HashMap();

现在在这个 HashMap 中,我希望键应该是 1 和 3,值应该是 2 和 2,即键 1 应该具有值 2,键 3 应该具有值 2,即重复次数应该是value 和重复的元素将作为 key 存储请告知如何实现这一点..!

【问题讨论】:

  • System.out.println(hm)
  • 请不要编辑您的问题以提出完全不同的问题。它使答案毫无用处。要将您的地图打印到控制台,请参阅我之前的评论。
  • @assylias 谢谢老兄,它有效..!但我正在寻找与 map.entry man.. 相关的东西!!
  • “我正在寻找与 map.entry 相关的内容” => 我不确定你在问什么。打印地图时,它会以{key = value} 格式打印条目列表。
  • 我既不酷也不酷——我只是不明白你在问什么。如果您需要有关 map.entry 的文档,请查看 javadoc

标签: java list collections hashmap


【解决方案1】:

您可以简单地遍历列表并:

  • 如果项目不在地图中,则使用 value = 1 创建它
  • 如果项目已经在地图中,则获取值,将其递增并放回地图中

ps:使用泛型是个好习惯:

List<Integer> list = new ArrayList<Integer> ();

Map<Integer, Integer> hm = new HashMap<Integer, Integer> ();

【讨论】:

  • 谢谢老兄,能否请您发布更新的代码,这将有助于理解很多..!
  • @DON 你现在有了算法,我建议你根据它写代码(它应该不超过5行)。如果您有问题,可以回来就该特定问题提出问题。
【解决方案2】:

类似这样的:

Map<Integer, Integer> hm = new HashMap<Integer, Integer>();

for (int i = 0; i < list.size(); ++i)
{
    // get a number from the list
    int number = list.get(i);

    // get the value linked to the key
    Integer mapval = hm.get(number);
    if (mapval == null)
    {
        // the value returned is null, which means that the key isn't in the map
        // the key wasn't found yet, so the number is zero times in it
        mapval = 0;
    }
    // increase the number of times the number occurs.
    hm.put(number, mapval + 1);
}

【讨论】:

    【解决方案3】:

    听起来您想要Multiset,例如Guava 中的那个。例如:

    Multiset<Integer> multiset = HashMultiset.create(list);
    

    那你可以拨打count:

    System.out.println(multiset.count(1)); // 2
    System.out.println(multiset.count(2)); // 1
    System.out.println(multiset.count(3)); // 2
    

    诚然,这并没有实现 Map - 但我怀疑它可以满足您的所有需求。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-19
      • 1970-01-01
      • 2020-05-18
      • 2017-07-30
      • 1970-01-01
      • 2012-10-13
      • 2023-03-18
      • 1970-01-01
      相关资源
      最近更新 更多