【问题标题】:Comparing Elements in the same ArrayLists and add to Hashmap比较相同 ArrayLists 中的元素并添加到 Hashmap
【发布时间】:2014-10-07 09:21:26
【问题描述】:

我有个小问题。

目前,我有一个 userList(String)和 timeLime(Integer)。 这些值是按顺序添加的,因此每个 .get(i) 将包含用户 (userList) 和他的时间 (timeList)。

由于名称ArrayList中可能存在重复的用户实例,所以我想总结一下timeList中每个用户的总时间,并将其放入<String, Integer>的hashmap中,但我不知道怎么做。

目前,我所做的是:

for (int i = 0; i < userList.size(); i++) {
    count = 0; 
    for (int j = 0; j <userList.size(); j++) {
        if (!userList.get(i).equals(userList.get(j))) {
            count++;
        }
    }
    if (count == userList.size() -1) {
        System.out.println("Adding in " + userList.get(i));
        map.put(userList.get(i), timeList.get(i));
    }
}

如果有匹配,我会被卡住。我不知道如何将时间加在一起并将其放入哈希图中。

我对 Java 不是很精通,希望得到一些帮助。提前致谢。

【问题讨论】:

  • 总时间是什么意思??这就是您想要实现的全部目标:删除重复项并计算有多少不同的元素?
  • @lostcder 添加可能输入和期望输出的示例。
  • @Alboz:例如。我在 nameList 中有一个重复的 Peter 条目,但时间不同(200、308)。我想将 (Peter, 508) 添加到哈希图中。但我也想添加所有不重复的条目。谢谢!

标签: java arraylist hashmap compare


【解决方案1】:

你想创建一个带有用户的 HashMap 和两个列表中可能出现的时间总和吗?如果是这种情况,下面的代码将为您完成。

    List<String> userList = new ArrayList<String>(Arrays.asList("ann", "john", "tim", "ann"));
    List<Integer> timeList = new ArrayList<Integer>(Arrays.asList(1, 2, 3, 5));

    Map<String, Integer> userTimeMap = new HashMap<String, Integer>();
    for (int i = 0; i < userList.size(); i++) {
        String user = userList.get(i);
        Integer time = userTimeMap.get(user);
        if (time == null) {
            userTimeMap.put(user, timeList.get(i));
        } else {
            userTimeMap.put(user, time + timeList.get(i));
        }
    }

结果:{john=2, ann=6, tim=3}

【讨论】:

  • 嗨,maheeka,感谢您的回复。这组代码确实有效。但只是想知道,如果一个键存在于哈希图中,向哈希图中添加相同的键会覆盖当前键吗?谢谢!
  • 是的,它会用新值覆盖以前使用相同键保存的任何内容。请投票:)
【解决方案2】:

我会这样做:

for (int i = 0; i < userList.size(); i++) {
    // check whether the entry is already there
    if (map.containsKey(userList.get(i))){
        // If already exists add
        map.put(userList.get(i), map.get(userList) + timeList.get(i));
    }else{
        // else make a new entry
        map.put(userList.get(i), timeList.get(i));
    }
}

【讨论】:

    猜你喜欢
    • 2017-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多