java - How to check for the same ID, and then increment for that particular id? -


i have hashmap, let's call hashmap, in method whereby i'll pass in string called id. have object, let's call userobject. want write output csv file, using below code:

for (userobject user: hashmap.get(id)) {             system.out.println(id);             writer.println(id + "," + user.gettime() + "," + user.getlat() + "," + user.getlng()); // csv         } 

but id may have multiples of same one. wanna whenever 1 id used for loop, there'll counter increments one. so, when same id used again, increment increase. however, when different id being used, increment operation. mean whenever loop running want count how many instances same id run. how can so? can't seem figure out logic.

p.s system.out.print(id) line of test code, output 1 chunk of ids.

**edit: logic work sql's count function, i'm not using sql, need in pure java

not sure if understand correctly, if want count elements in hashmap, can try this.

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 3 }  static int count(string id, map<string, string> map) {     int = 0;     (string val : map.values()) {         if (id.equals(val))             i++;     }     return i; } 

edit: if want wrap funcionality every time touch particular value, counter increments, can achieve approach.

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) {         (string value : map.values()) {             system.out.println(value);              if (!count.containskey(value)) {                 count.put(value, 1);             } else {                 int = 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 3     system.out.println(id.count("c")); // output 2 } 

Comments

Popular posts from this blog

java - Date formats difference between yyyy-MM-dd'T'HH:mm:ss and yyyy-MM-dd'T'HH:mm:ssXXX -

c# - Get rid of xmlns attribute when adding node to existing xml -