我有一个 hashmap,我们称之为 hashMap
,它在一个方法中,我将传入一个名为 id
的字符串。我还有一个对象,我们将其称为 UserObject
。所以目前我想做的是将输出写入 csv 文件,使用以下代码:
for (UserObject user: hashMap.get(id)) {
System.out.println(id);
writer.println(id + "," + user.getTime() + "," + user.getLat() + "," + user.getLng()); // csv
}
但是这个id可能有多个相同的。所以我想做的是每当一个 id 用于 for 循环时,就会有一个计数器加一。所以,当再次使用相同的id时,增量会增加。然而,当使用不同的id时,这是另一种增量操作。所以基本上我的意思是,每当 for 循环运行时,我想计算有多少个相同 id 的实例将运行。我怎样才能这样做呢?我似乎无法弄清楚其中的逻辑。
P.S System.out.print(id)
是一行测试代码,输出是一大块 ID。
**编辑:逻辑的工作方式类似于 SQL 的计数函数,但我没有使用 SQL,我只需要纯 java 中的它
最佳答案
不确定我理解是否正确,但是如果你想计算 HashMap 中的元素,你可以尝试这样的方法。
public static void main(String[] args) {
Map<String, String> map = new HashMap<String, String>();
map.put("1", "A");
map.put("2", "B");
map.put("3", "C");
map.put("4", "B");
map.put("5", "B");
map.put("6", "C");
System.out.println(count("B", map)); // output is 3
}
static int count(String id, Map<String, String> map) {
int i = 0;
for (String val : map.values()) {
if (id.equals(val))
i++;
}
return i;
}
编辑:如果您想包装每次触摸特定值时计数器递增的功能,您可以通过这种方法来实现。
public class IdHandler {
Map<String, Integer> count = new HashMap<String, Integer>();
public int count(String id) {
return count.get(id);
}
public void export(Map<String, String> map) {
for (String value : map.values()) {
System.out.println(value);
if (!count.containsKey(value)) {
count.put(value, 1);
} else {
int i = count.get(value);
count.put(value, ++i);
}
}
}
}
public static void main(String[] args) {
Map<String, String> map = new HashMap<String, String>();
map.put("1", "A");
map.put("2", "B");
map.put("3", "C");
map.put("4", "B");
map.put("5", "B");
map.put("6", "C");
IdHandler id = new IdHandler();
id.export(map);
System.out.println(id.count("B")); // output is 3
System.out.println(id.count("C")); // output is 2
}
关于java - 如何检查相同的 ID,然后为该特定 id 递增?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32691913/